[Django]-Optional get parameters in django?

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'),
๐Ÿ‘คTodd Gardner

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 ๐Ÿ™‚

๐Ÿ‘คVisgean Skeloru

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

๐Ÿ‘คCarl Meyer

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'),
๐Ÿ‘คhughdbrown

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!

๐Ÿ‘คEagllus

-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 ๐Ÿ™‚

๐Ÿ‘คPopara

-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โ€™

๐Ÿ‘คPstrazzulla

Leave a comment