Search code examples
djangodjango-viewsdjango-urls

django - url with no argument to take a default value


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


Solution

  • 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.