Alex Rivera | Logout

Optional get parameters in django?

Asked 2009-08-30T01:43:34.243
26

Can someone please explain how you can write a url pattern and view that allows optional parameters? I've done this successfully, but I always break the url template tag.

Here's what I have currently:

Pattern

(r'^so/(?P<required>\d+)/?(?P<optional>(.*))/?$', 'myapp.so')

View

def so(request, required, optional):

If I use the url template tag in this example providing both arguments, it works just fine; however, if I omit the optional argument, I get a reversing error.

How can I accomplish this?

Thanks, Pete

Edit
Report

1 Answer

18

Django urls are polymorphic:

url(r'^so/(?P<required>\d+)/$', 'myapp.so', name='sample_view'),
url(r'^so/(?P<required>\d+)/(?P<optional>.*)/$', 'myapp.so', name='sample_view'),

its obious that you have to make your views like this:

def sample_view(request, required, optional = None):

so you can call it with the same name and it would work work url resolver fine. However be aware that you cant pass None as the required argument and expect that it will get you to the regexp without argument:

Wrong:

{% url sample_view required optional %}

Correct:

{% if optional %}
    {% url sample_view required optional %}
{% else %}
    {% url sample_view required %}
{% endif %}

I dont know whether this is documented anywhere - I have discovered it by accident - I forgot to rewrite the url names and it was working anyway :)

answered 2012-01-24T01:46:59.743

Your Answer