Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access kwargs from a URL in a Django template

Tags:

Can I access value of a named argument (from the URL) in a Django template?

Like can I access the value of this_name below from a django template?

url(r'^area/(?P<this_name>[\w-]+)/$', views.AreaView.as_view(), name="area_list") 

I could get the whole URL path and break it up but wanted to check if there's a straight forward way to do that, since it already has a name.

Passing it down in the context data from the view may be an alternative but not sure if I do need to pass it down since I'd guess the template would already have it somehow? Couldn't find a direct method in the request API though.

like image 424
Anupam Avatar asked Jul 14 '17 08:07

Anupam


People also ask

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

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 .

What is {% include %} in Django?

Usage: {% extends 'parent_template. html' %} . {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it.


Video Answer


1 Answers

In the view, you can access the URL args and kwargs as self.args and self.kwargs.

class MyView(View):     def my_method(self):         this_name = self.kwargs['this_name'] 

If you only want to access the value in the template, then you don't need to make any changes in the view. The base get_context_data method adds the view to the context as view, so you can add the following to your template:

{{ view.kwargs.this_name }} 
like image 189
Alasdair Avatar answered Oct 12 '22 22:10

Alasdair