如何使用Django获取当前urlname? [英] How to get the current urlname using Django?

查看:284
本文介绍了如何使用Django获取当前urlname?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据当前的url动态构建一个url。使用 {%url%} 标签是最简单的方法,但是我需要当前的url名称才能动态生成新的URL。



如何获取连接到导致当前视图的urlconf的URL名称?



编辑:我知道我可以使用 get_absolute_url 手动手工处理网址,但我宁愿避免使用它,因为它是演讲的一部分,我只想演示一种方法来构建网址。 / p>

学生知道如何使用 {%url%} 。他们知道面对一个问题,当他们必须生成一个更完整的网址基于当前的。最简单的方法是再次使用 {%url%} 。由于我们已经命名了url,我们需要知道如何获取名为当前视图的url的名称。



编辑2:另一个用例是根据基本模板不同地显示基本模板的部分。还有其他方法可以使用(使用CSS和{%block%}),但有时候如果viewname与链接匹配,则可以删除base.html菜单条目的标签。

解决方案

我不知道这个功能是Django的一部分,但是作为以下文章显示,可以在视图中实现如下:

  from django.core.urlresolvers import resolve 
current_url = resolve(request.path_info).url_name

如果您需要在每个模板中编写模板请求都可以。


I have to build an url dynamically according to the current url. Using the {% url %} tag is the easiest way to do it, but I need the current url name to generate the new one dynamically.

How can I get the url name attached to the urlconf that leads to the current view?

EDIT : I know I can manually handcraft the url using get_absolute_url but I'd rather avoid it since it's part of a lecture and I would like to demonstrate only one way to build urls.

The students know how to use {% url %}. They are know facing a problem when they have to generate a more complete url based on the current one. The easiest way is to use {% url %} again, with some variations. Since we have named url, we need to know how to get the name of the url that called the current view.

EDIT 2: another use case is to display parts of the base template différently according to the base template. There are other ways to do it (using CSS and {% block %}, but sometime it just nice to be able to remove the tag of the menu entry of base.html if the viewname match the link.

解决方案

I don't know how long this feature has been part of Django but as the following article shows, it can be achieved as follows in the view:

   from django.core.urlresolvers import resolve
   current_url = resolve(request.path_info).url_name

If you need that in every template, writing a template request can be appropriate.

这篇关于如何使用Django获取当前urlname?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆