Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
713 views
in Technique[技术] by (71.8m points)

Access kwargs from a URL in a Django template

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...