Django - 将URL "name" 属性传递给视图
我创建了一个这样的URL:
urls.py
url(r'^authors', GenericView.as_view(model=Author, context_object_name='authors_list',
success_url=reverse_lazy('author_link'),
template_name='app/authors.html'), name='author_url_name'),
我想在视图中获取这个URL的名称,并把它放在一个变量里。在这个例子中,就是'author_url_name'。
我需要这个变量的视图函数如下:
views.py
def get_context_data(self, **kwargs):
context = super(AuthorClass, self).get_context_data(**kwargs)
context['action'] = reverse_lazy('author_url_name')
return context
现在这样是可以工作的,但我想用某种方法来替换掉'author_url_name',这样我就能直接得到它。
谢谢你的时间!!
1 个回答
3
这个链接 https://stackoverflow.com/a/17614086/183948 给你提供了答案。
从Django 1.5开始,你可以通过请求对象来访问这个内容。
current_url = request.resolver_match.url_name
你可以查看这个文档了解更多信息 https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.HttpRequest.resolver_matc