Search code examples
regexdjangourl-pattern

What's the correct regex for a required string and optional string in Django?


So in my Django URLS I want to be able to support:

mysite.com/section

mysite.com/section/

mysite.com/section/sectionAlphaNum

mysite.com/section/sectionAlphaNum/

I currently have as the URL pattern:

(r'^section/(?P<id>\s?)?', section)

Which should make section/ required and anything after optional, but it never seems to catch whatever sectionAlphaNum I enter in. In my views.py file I have

def section(request,id):
    if id == '':
        # Do something with id
    else:
        # Do default action

But it never seems to get into the top if branch where it does something with the id


Solution

  • (r'^section(?:/(?P<id>\w+))?/$', section)
    

    Notice the last ? to make the whole (?:/(?P<id>\w+)) optional.

    Other answers are missing the ? or they don't make one of the slashes (/) optional like I do with the first one in (?:/( ...

    r'^section/(?:(?P<id>\w+)/)?$'  # same result, last '/' optional.
    

    And make the parameter optional in the function as well:

    def section(request, id=None):
        # ...