Jared Joke
Jared Joke

Reputation: 1356

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

Upvotes: 1

Views: 87

Answers (4)

Adri&#225;n
Adri&#225;n

Reputation: 6255

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

Upvotes: 0

HankMoody
HankMoody

Reputation: 3174

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.

Upvotes: 1

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15320

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

Upvotes: 1

Phil
Phil

Reputation: 887

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

Upvotes: 1

Related Questions