Access kwargs from a URL in a Django template
Asked Answered
D

1

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.

Dialogize answered 14/7, 2017 at 8:59 Comment(1)
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 questionLollipop
J
54

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 }}
Jokjakarta answered 14/7, 2017 at 9:13 Comment(2)
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 anythingDialogize
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')})Jokjakarta

© 2022 - 2024 — McMap. All rights reserved.