Search code examples
pythondjangodjango-viewsdjango-urls

Django optional URL parameters


I have a Django URL like this:

url(
    r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$',
    'tool.views.ProjectConfig',
    name='project_config'
),

views.py:

def ProjectConfig(request, product, project_id=None, template_name='project.html'):
    ...
    # do stuff

The problem is that I want the project_id parameter to be optional.

I want /project_config/ and /project_config/12345abdce/ to be equally valid URL patterns, so that if project_id is passed, then I can use it.

As it stands at the moment, I get a 404 when I access the URL without the project_id parameter.


Solution

  • Updated 2023

    This answer is outdated but still gets activity.

    See @j-i-l's answer below for Django > 2 and reference to current docs.

    Original 2013 Answer

    There are several approaches.

    One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
    Making a Regex Django URL Token Optional

    Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.

    urlpatterns = patterns('',
        url(r'^project_config/$', views.foo),
        url(r'^project_config/(?P<product>\w+)/$', views.foo),
        url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
    )
    

    Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:

    def foo(request, optional_parameter=''):
        # Your code goes here