In Django, what's the best way to handle optional url parameters from the template?

Posted by Thierry Lam on Stack Overflow See other posts from Stack Overflow or by Thierry Lam
Published on 2010-06-15T20:18:47Z Indexed on 2010/06/15 20:22 UTC
Read the original article Hit count: 597

I have the following type of urls which are both valid:

hello/
hello/1234/

My urls.py has the following:

urlpatterns = patterns('hello.views',
    url(r'^$', 'index', name='index'),
    url(r'^(?P<user_id>\d+)/$', 'index', name='index'),
)

In my views.py, when I pass user_id to the template, it defaults to 0 if not specified.

My template looks like the following, I'm using namespace hello for my hello app:

{% url hello:index user_id %}

If user_id is not specified, the url defaults to hello/0/. The only way I can think of preventing the default 0 from showing in the url is by an if stmt:

{% if user_id %}
  {% url hello:index user_id %}
{% else %}
  {% url hello:index %}
{% endif %}

The above will give me hello/ if there are no user_id and hello/1234/ if it's present. Is the above solution the best way to solve this issue?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-templates