28

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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Anupam
  • 14,950
  • 19
  • 67
  • 94
  • this_name will be passed as context and then as it can be used in template. I don't understand why you can't access. Or what other way you want to access it. May be a use case complete will clarify this question – Arpit Solanki Jul 14 '17 at 09:03

1 Answers1

52

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 }}
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I had to do this for another template that is not based on a class based view but somehow cant figure out how to access kwargs there. Is the method different for non class-based view? Searched in the docs but couldnt find anything useful yet. I tried just `kwargs.this_name` but that also doesnt return anything – Anupam Jul 28 '17 at 14:33
  • 6
    If you have a view function `def my_view(request, myvar, *args **kwargs):` then it's up to you to include the variables in the template context, e.g. `return render(request, 'mytemplate.html', {'myvar': myvar, 'foo': kwargs.get('foo')})` – Alasdair Jul 28 '17 at 16:17