Optional get parameters in django?


Question

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

1
25
8/30/2009 1:43:34 AM

Accepted Answer

I generally make two patterns with a named url:

url(r'^so/(?P<required>\d+)/$', 'myapp.so', name='something'),
url(r'^so/(?P<required>\d+)/(?P<optional>.*)/$', 'myapp.so', name='something_else'),
38
8/30/2009 1:48:34 AM

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 :)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon