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
{% 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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With