django-反向解析
views.py
#url_反向解析
def test_url(request):
return render(request,‘test_url.html‘)
def test_url_result(request):
return HttpResponse(‘--------响应结果-----‘)
def test_url_aj(request,id):
return HttpResponse(‘TEST_URL_AJ%s‘%id)
def test_url_strint(request,id,info):
return HttpResponse(‘TEST_URL_AJ%d%s‘%(id,info))
url.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
#路由
path(‘test_url/‘,views.test_url),
path(‘test_url_result/‘,views.test_url_result),
#反向解析
path(‘test_url_aj/<int:id>‘,views.test_url_aj,name=‘test_url_aj‘),
path(‘test_url_strint/<int:id>/<str:info>‘,views.test_url_strint,name=‘test_url_strint‘),
#views中的反向解析
path(‘test_url_redirect‘,views.test_url_redirect)
]
test_url.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test_url</title>
</head>
<body>
<h3>反向解析</h3>
<div>
<a href="{% url ‘test_url_aj‘ ‘155‘ %}">反向解析1</a>
<a href="{% url ‘test_url_strint‘ ‘1‘ ‘today‘ %}">反向解析2</a>
<a href="{% url ‘test_url_strint‘ info=‘today‘ id=‘2‘ %}">反向解析3</a>
</div>
</body>
</html>
显示页面html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test_url</title>
</head>
<body>
<h3>反向解析</h3>
<div>
<a href="/test_url_aj/155">反向解析1</a>
<a href="/test_url_strint/1/today">反向解析2</a>
<a href="/test_url_strint/2/today">反向解析3</a>
</div>
</body>
</html>
views视图反向解析-重定向
views.py
#视图内反向解析--重定向
def test_url_redirect(request):
from django.urls import reverse
#reverse(‘test_url‘,argse=[],kwargs={})
url=reverse(‘test_url_strint‘,kwargs={‘id‘:‘15‘,‘info‘:‘tom‘})
print(url)
return HttpResponseRedirect(url)
url.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
#路由
path(‘test_url/‘,views.test_url),
path(‘test_url_result/‘,views.test_url_result),
#反向解析
path(‘test_url_aj/<int:id>‘,views.test_url_aj,name=‘test_url_aj‘),
path(‘test_url_strint/<int:id>/<str:info>‘,views.test_url_strint,name=‘test_url_strint‘),
#views中的反向解析
path(‘test_url_redirect‘,views.test_url_redirect)
]
页面显示