Feature: URL template tag, optional parameters

548 views
Skip to first unread message

erez....@gmail.com

unread,
Jun 4, 2015, 5:44:54 AM6/4/15
to django-d...@googlegroups.com
Hi,

AFAIK, the recommended way in Django to handle multiple urls with the same view, is to have optional parameters. (https://docs.djangoproject.com/en/1.8/topics/http/urls/#specifying-defaults-for-view-arguments)

For example,

in url.py:

url
(r'^blog/page/(?P<page_pk>\d+)/$', views.page, name='view-page'),
url
(r'^blog/page/(?P<page_pk>\d+)/(?P<page_slug>[a-zA-Z0-9_.-])/$', views.page, name='view-page'),

in views.py:
# View (in blog/views.py)
def page(request, page_pk, page_slug=""):


However, in the templates, the url template tag can't accept optional parameters.
So instead of writing {% url 'view-page' page_pk page_slug %}, you need to write {% if page_slug=="" %}{% url 'view-page' page_pk %}{% else %}{% url 'view-page' page_pk page_slug %}{% endif %}
On the project I'm working on I have 2 or more optional parameters, and it's a real nuisance.

The url tag could have done this logic by itself. If any of its inputs are blank or none, disregard it.

Same question from Stack Overflow (not asked by me) : http://stackoverflow.com/questions/16870884/url-template-optional-param

Thanks

Tim Graham

unread,
Jun 11, 2015, 3:07:50 PM6/11/15
to django-d...@googlegroups.com
I think you'll have to try implementing it to see if it's feasible.

Joachim Jablon

unread,
Jun 18, 2015, 7:18:34 AM6/18/15
to django-d...@googlegroups.com
But what if we need to distinguish between "" and None ?

E.g. :

url(r'^blog/page/(?P<page_pk>\d+)/$', views.page, name='view-page'),

url
(r'^blog/page/(?P<page_pk>\d+)/subpage(?P<option>.*)/$', views.page, name='view-page'),

So that makes :
reverse("view-page", page_pk=12) == "blog/page/12/"
reverse("view-page", kwargs={page_pk:12, option:""}) == "blog/page/12/subpage/"

How would you distinguish between those 2 in the template ?

Joachim Jablon
Ingénieur Systèmes
+33 (0)6 75 66 76 84
+33 (0)1 84 17 31 20

SMART IMPULSE

48 rue René Clair
75018 PARIS

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/9c67b646-ee16-4f82-a545-9e4178d4e7dc%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages