In Django, what's the best way to handle optional url parameters from the template?
- by Thierry Lam
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?