app2.urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('index', views.index, name='index'),
path('url_reverse', views.url_reverse, name='app2_url_reverse'), # 使用reverse()方法反向解析 ,name对于视图的reverse("app2_url_reverse")
]
app2.views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
def index(request):
return HttpResponse("app2 的index")
# 反向解析
def url_reverse(request):
# 使用reverse()方法反向解析
print('解析结果:'+ reverse("app2_url_reverse")) # 使用reverse()方法反向解析 ,reverse("app2_url_reverse") 对应urls的 name='app2_url_reverse'
return render(request, "2/url_reverse.html")
templates1/2/url_reverse.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div style="color:red;font-size:24px;">url_reverse</div>
<div>
在html中使用url标签进行反向解析
<br>
{%url 'app2_url_reverse'%}
</div>
</body>
</html>