在Django的模板语言中,你可以使用 {% url [viewname] [args] %} 生成带有参数的特定视图的 URL。如何在 Python 代码中以编程方式执行相同的操作?

我需要的是创建一个菜单项列表,其中每个项目都有名称、URL 和活动标志(无论是否是当前页面)。这是因为在 Python 中执行此操作比模板语言要干净得多。

有帮助吗?

解决方案

如果您需要使用类似的东西 {% url %} 代码中的 template 标签,Django 提供了 django.core.urlresolvers.reverse(). 。这 reverse 函数具有以下签名:

reverse(viewname, urlconf=None, args=None, kwargs=None)

https://docs.djangoproject.com/en/dev/ref/urlresolvers/

其他提示

我在我的方法中使用了两种不同的方法 models.py. 。第一个是 permalink 装饰器:

from django.db.models import permalink

def get_absolute_url(self): 
    """Construct the absolute URL for this Item."""
    return ('project.app.views.view_name', [str(self.id)])
get_absolute_url = permalink(get_absolute_url)

您也可以致电 reverse 直接地:

from django.core.urlresolvers import reverse

def get_absolute_url(self): 
    """Construct the absolute URL for this Item."""
    return reverse('project.app.views.view_name', None, [str(self.id)])

请注意,使用 reverse() 要求您的 urlconf 模块 100% 无错误并且可以处理 - 没有 ViewDoesNotExist 错误左右,或者你会得到可怕的 NoReverseMatch 异常(模板中的错误通常会默默地失败,从而导致 None).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top