从Django模板中的URL访问kwarg [英] Access kwargs from a URL in a Django template
问题描述
我可以在Django模板中访问命名参数的值(从URL)吗?
Can I access value of a named argument (from the URL) in a Django template?
就像我可以访问 this_name的值一样从下面的Django模板中获取?
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")
我可以获取整个URL路径并将其分解,但是想检查是否有一种直接的方法,因为它已经有了一个名称。
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.
将其从视图中传递到上下文数据中可能是另一种选择,但是不确定我是否确实需要将其传递出去,因为我猜想模板已经具有不知何故?在请求API <中找不到直接方法/ a>。
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.
推荐答案
在视图中,您可以访问URL args
和 kwargs
作为 self.args
和 self.kwargs
。
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']
如果您只想访问模板中的值,则您无需在视图中进行任何更改。基本 get_context_data
方法将视图作为 view
添加到上下文中,因此您可以将以下内容添加到模板中:
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 }}
这篇关于从Django模板中的URL访问kwarg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!