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

How to check name of Django url in view

说这是我的 url:

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

是否可以在视图和中间件中检查此文本 = "mainApp_views.homepage"?

提前致谢,

你想要这样的东西

from django.urls import resolve


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

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

从 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