Django在views.py中引用url

时间:2014-12-23 20:00:29

标签: python django

在Django中,我设置了urls.py,如下所示:

url(r'^example/$',   ExampleView.as_view(), name='example'),
url(r'^example2/$',   AnotherView.as_view(), name='example2'),

“example2”的位置如下:'http://localenv.com/example2'。

在我的views.py中,我想返回对“example2”链接的引用。让我解释一下:

class ExampleView(TemplateView):
    some_var = REFERENCE TO EXAMPLE 2 URL
    print some_var

我希望打印声明返回“http://localenv.com/example2

任何帮助?

2 个答案:

答案 0 :(得分:5)

您想要使用reverse()

from django.core.urlresolvers import reverse

class ExampleView(TemplateView):
    some_var = reverse('example2')
    print some_var

编辑:

如果您想要绝对的uri,可以使用build_absolute_uri

进行构建
from django.core.urlresolvers import reverse

class ExampleView(TemplateView):
    some_var = request.build_absolute_uri(reverse('example2'))
    print some_var

答案 1 :(得分:0)

您可以查看urlresolvers。但它只会提供 URI ,您必须手动添加“http://localenv.com ...”。

相关问题