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

1

7 Answers 7

39

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'),
4
  • 2
    Yes, this is the usual way to do it. The URL-reverser has only limited smarts about regexes (it doesn't implement a full regex parser), and it can't handle optional parts. You are free to use the full power of regexes in your URL patterns, but then you give up URL reversing.
    – Carl Meyer
    Aug 30, 2009 at 14:06
  • Thanks, this is what I was looking for. Was surprised to learn I needed two separate URLs.
    – slypete
    Sep 2, 2009 at 6:23
  • See here for another way to do this (do not know which versions of Django this approach is compatible with - I use 1.4 though): gist.github.com/1028897
    – floer32
    Nov 8, 2012 at 18:39
  • I had a pain trying to get optional parameters going by using "?", it worked in most cases but not for all, problems with reversing urls. This is the cleanest solution.
    – radtek
    Aug 18, 2014 at 20:51
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 :)

5

Others have demonstrated the way to handle this with two separate named URL patterns. If the repetition of part of the URL pattern bothers you, it's possible to get rid of it by using include():

url(r'^so/(?P<required>\d+)/', include('myapp.required_urls'))

And then add a required_urls.py file with:

url(r'^$', 'myapp.so', name='something')
url(r'^(?P<optional>.+)/$', 'myapp.so', name='something_else')

Normally I wouldn't consider this worth it unless there's a common prefix for quite a number of URLs (certainly more than two).

2
  • Thanks Carl, this looks like it will come in handy too.
    – slypete
    Sep 2, 2009 at 6:23
  • you can use patterns to save having to create a new file: url(r'...', include(patterns('', url(...), url(...)))). See here
    – Patrick
    Mar 29, 2014 at 1:33
1

Why not have two patterns:

(r'^so/(?P<required>\d+)/(?P<optional>.*)/$', view='myapp.so', name='optional'),
(r'^so/(?P<required>\d+)/$', view='myapp.so', kwargs={'optional':None}, name='required'),
1
  • It doesn't matter which order you put these URL patterns in. They both are bounded with $ at the end, so there can be no ambiguity. There are, of course, similar situations where it would matter (if the shorter pattern were unbounded, for instance).
    – Carl Meyer
    Aug 30, 2009 at 14:04
1

For anyone who is still having this problem. I use Django 1.5 (updated: using 1.8) and it's still working fine.

I use:

urls.py

url(r'^(?P<app_id>\d+)/start/+(?P<server_id>\d+)?', views.restart, name='restart')

Then when I want to have the two urls

/1/start/2

and

/1/start

I use:

{% url '<namespace>:start' app.id %}
{% url '<namespace>:start' app.id server.id %}

This will create the urls

/1/start/2 and 
/1/start/ <- notice the slash.

If you create a url manually you have to keep the / in mind.

I hoop this helps anyone!

-1

in views.py you do simple thing.

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

And when you dont get optional param in url string it will be None in your code.

Simple and elegant :)

3
  • In which version of Django it works? I've 1.5 this don't work without changes in url.py Oct 20, 2013 at 8:09
  • This works for views.py methods. And it is pretty depreciated since Django changed a lot of stuff in terms of URL management and applying views. [eg. Class based views];
    – Popara
    Oct 24, 2013 at 8:37
  • You cannot do that in django, it first look at url.py & won't find any pattern that matches the url. As this on is in views.py and won't run until after a pattern is found
    – OMY
    Jun 22, 2014 at 11:21
-2

Depending on your use case, you may simply want to pass a url parameter like so:

url/?parameter=foo

call this in your view:

request.REQUEST.get('parameter')

this will return 'foo'

1
  • My question was regarding passing the optional parameter to the view function as well as using it with the url template tag.
    – slypete
    Nov 11, 2014 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.