Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django {% url %} tag without parameters

Tags:

django

I have a url defined as follows:

url(r'^details/(?P<id>\d+)$', DetailView.as_view(), name='detail_view'),

In my templates, I want to be able to get the following url: /details/ from the defined url.

I tried {% url detail_view %}, but I get an error since I am not specifying the id parameter.

I need the url without the ID because I will be appending it using JS.

How can I accomplish this?

like image 714
AlexBrand Avatar asked Aug 29 '12 18:08

AlexBrand


People also ask

What does {% %} mean in Django?

This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.

What {% include %} does?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.

Which method is used instead of PATH () in URLs py to pass in regular expressions as routes?

To do so, use re_path() instead of path() . In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern) , where name is the name of the group and pattern is some pattern to match.


1 Answers

Just add this line to your urls.py:

url(r'^details/$', DetailView.as_view(), name='detail_view'),

or:

url(r'^details/(?P<id>\d*)$', DetailView.as_view(), name='detail_view'),

(This is a cleaner solution - thanks to Thomas Orozco)

You'll need to specify that id is optional in your view function:

def view(request, id=None):
like image 197
ldiqual Avatar answered Sep 19 '22 08:09

ldiqual