如何在Django视图中检查url的名称

3

我这是我的网址:

url(r'^$', mainApp_views.homepage),

在视图和中间件中检查文本“mainApp_views.homepage”是否可行?

谢谢提前。

2个回答

2
你想要类似这样的东西。
from django.urls import resolve


def your_view(request):
    # resolve the url from the path
    url_name = resolve(request.path).url_name

您可能也想在URL中添加名称 name='home'


@python_beg2 哈哈,不完全是这样的 =) 我曾经也遇到过同样的问题 =D - The_Cthulhu_Kid
1
我认为现在应该是 from django.urls import resolve - Trey Piepmeier
@TreyPiepmeier 可能吧,不过这个是1.10/1.11的版本,谢谢 =) - The_Cthulhu_Kid

0

从Django 2.0开始,您需要从django.urls导入resolve

from django.urls import resolve

def your_view(request):
    url_name = resolve(request.path).url_name
    print(url_name) #prints the "name" attribute in your urlpatterns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接