Question

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

Was it helpful?

Solution 4

(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):
    # ...

OTHER TIPS

Can you try the following syntax: (r'^section/(?P<id>\w+)/$', section)?

In regular expressions the ^ and $ represent the start and end of the string respectively.

Hence the URL to display /section/ would be:

(r'^section/$', section_view)

while the URL to display a specific section /section/section-id/ would be :

(r'^section/(?P<section_id>\w+)$', section_detail_view)

Ideally you have separate views in your views.py:

def section_view(request):
    # show page about the various sections

def section_detail_view(request, section_id):
    # show page about specific section by section_id

urls.py:

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

views.py:

def section(request, id=None):
    if id is None:
       ...
    else:
       ...

To append just slash (from /section to /section/) enable CommonMiddleware in Your settings' MIDDLEWARE_CLASSES.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top