Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 215
Aamu Avatar asked Dec 02 '13 00:12

Aamu


People also ask

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

How do I change the default URL in Django?

Set up app folder's urls.py and html files In the same directory, you should have a file named views.py. We will create a function called index which is what makes the http request for our website to be loaded. Now, we've set it up such that http://127.0.0.1:8000/homepage will render the HTML template index.

How do I reference a URL in Django?

The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py . Listing 2-16 shows how to name a project's home page, as well as how to reference this url from a view method or template.


1 Answers

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.

like image 99
Peter DeGlopper Avatar answered Nov 08 '22 22:11

Peter DeGlopper