Question

I have created a Django app with the URL structure:

eventdetails/?event_id=94099

This would take me to the index page of the event details app. However My app has sections, and each section needs the event_id to use.

Therefore I need a url structure like:

eventdetails/who/?event_id=94099

So I can still access the event ID.

Could anyone advise me how to create the links for the navigation or a better way of doing this.

Thanks,

Was it helpful?

Solution

django's URL maps do not take into account the query string, which is passed as is to any view that is mapped.

In practical terms, this means that if you have:

url(r'^eventdetails/who/$', 'event_who', name='e-who'),
url(r'^eventdetails/$', 'event_detail', name='e-detail')

Then both your view methods will have access to the query string:

def event_detail(request):
    id = request.GET.get('event_id')

def event_who(request):
    id = request.GET.get('event_id')
    if not id:
        print 'No ID!'
    else:
        print 'do stuff'
    return render(request, 'who.html')

You can also add the event id as part of the url itself, for example eventdetails/94099/:

url(r'^eventdetails/(?P<id>\d+)/$', 'event_detail', name='e-detail')

Then your views will be:

def event_detail(request, id=None):
    if not id:
        print 'No ID!'
    else:
        print 'do stuff'
    return render(request, 'detail.html')

The other benefit you get is that you can easily generate URLs for your events in your templates and views:

<ul>
{% for event in events %}
    <li><a href="{% url 'e-detail' id=event.pk %}"> {{ event.name }}</a></li>
{% endfor %}
</ul>

In your view:

def go_to_event(request, id):
    return redirect('e-detail', id=id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top