7

Suppose, this is an url which takes an argument (here, book_id) and pass the value to the views:

url(r'^/(?P<book_id>\w+)/$', 'pro.views.book', name='book'),

Is it possible for a url which takes an argument, but, if no argument is given, take a default value. If possible may be in the views too. I am sorry if this is a lame question, but I really need to know. Any help or suggestion will be grateful. Thank you

2
  • from documentation Commented Dec 2, 2013 at 0:25
  • Should have looked into the docs. Thank you! Commented Dec 2, 2013 at 9:23

2 Answers 2

13

Make the capturing pattern optional, and remember to deal with a trailing slash appropriately. I'd find a noncapturing group around the capturing group the safest way to do that:

url(r'^(?:(?P<book_id>\w+)/)?$', 'pro.views.book', name='book'),

Then in the views, declare a default for the argument:

def book(request, book_id='default'):

If you find that URL pattern ugly, you can bind two regexps to the same view function:

url(r'^(?P<book_id>\w+)/$', 'pro.views.book', name='book'),
url(r'^$', 'pro.views.book', name='default_book'),

Following Alasdair's reminder, I have removed the leading slash. I thought that looked odd.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 including both approaches, personally I much prefer two regexps
Yeah, I tend to use that approach myself - though that's partly just because I'm usually too lazy to refresh my memory on noncapturing group syntax.
Woah! I would have never thought of that. Thank you so much!
1

this very old topic but maybe someone want known hot to do this today.

First method is add in view default val: def someView(request, val1=0, val2=0):

and create two url paths to this view: path('myurl/',view.someView, name='someview'), path('myurl/int:val1/int:val2/',view.someView, name='someview),

Another methos is use in template link like this: href="{% url 'someView' %}?val1=1200"

and check in view is val1 exists if request.GET.get('val1'): doSomething

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.