Raunak Agarwal
Raunak Agarwal

Reputation: 7228

Django: How can I make a part of the URL optional

I have a url in which I would like to make the status token optional. If the status token is not provided in the url I give a default value in the view method argument. I tried replacing the token with this (?:/(?P<status>\d+))?$ but doesn't seems to work well. Thanks

url(r'^(?P<status>\d+)/$', frequest_list, name="frequest_list"),

def request_list(request, status=1):
 ...
 ...

Update: This was the pattern I was trying:

url(r'^(?:/(?P<status>\d+))?$', frequest_list, name="frequest_list"),

So, if I try localhost/features/ works well

But if I do localhost/features/1/ it fails

Upvotes: 2

Views: 1323

Answers (2)

jdi
jdi

Reputation: 92567

I use single url optional captures in some of my projects, and they work fine. You might want to adjust your pattern to make the trailing / optional. I think that is what is causing your url to not match. Django does have an "APPEND_SLASH" settings bool that will add that on to your urls if they are missing it and don't match:

url(r'^features(?:/(?P<status>\d+))?/?$', frequest_list, name="frequest_list")

The optional / could probably also be written like this:

url(r'^features/?(?:(?P<status>\d+)/?)?$', frequest_list, name="frequest_list")

Upvotes: 1

mVChr
mVChr

Reputation: 50185

Just create a second url entry that calls the same view:

url(r'^features/$', frequest_list, name="frequest_list_default"),
url(r'^features/(?P<status>\d+)/$', frequest_list, name="frequest_list"),

Upvotes: 3

Related Questions