在urls.py文件中,在進行url映射時,爲請求的url命個名,以便在模板頁面或者views.py視圖中能夠進行反向解析,同時在修改了url映射的請求路徑,名稱不變的狀況下,再也不修改模板頁面或者視圖中的數據,項目不受影響正常執行!url標籤中使用模板變量和普通標籤參數同樣,空格隔開,{{ % url 別名 %}}便可。html
url(r'^url_reverse/', views.url_reverse,name="view_reverse"), url(r'^login/', views.login,name="logining"),
url_reverse.htmlpython
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>頁面url反向解析</title> 6 </head> 7 <body> 8 <h1><a href="{% url "logining" %}">登陸</a></h1> 9 {#{% url "loging" %}經過url反向解析名稱"loging",直接獲取到urls.py模塊中與之對應的url路徑"login/"#} 10 </body> 11 </html>
login.htmldjango
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>login</title> 6 </head> 7 <body> 8 <form action="http://127.0.0.1:8888/login/" method="post"> 9 {% csrf_token %}<!--在進行模板渲染時會自動生成一個隱藏的input標籤--> 10 <table> 11 <tr> 12 <td>用戶名:</td> 13 <td><input type="text" name="username"></td> 14 </tr> 15 <tr> 16 <td>密碼:</td> 17 <td><input type="text" name="userpsd"></td> 18 </tr> 19 <tr> 20 <td><input type="reset"></td> 21 <td><input type="submit" ></td> 22 </tr> 23 </table> 24 </form> 25 </body> 26 </html> 27
views.py視圖中url反向解析:post
1 from django.shortcuts import render, HttpResponse, redirect 2 from django.urls import reverse 3 4 def url_reverse(request): 5 return render(request,"url_reverse.html") 6 7 def login(request): 8 if request.method=="GET": 9 return render(request,"login.html") 10 elif request.method=="POST": 11 name=request.POST.get("username") 12 psd=request.POST.get("userpsd") 13 if name=="yang" and psd=="123": 14 return HttpResponse("<h1>Success!</h1>") 15 else: 16 return redirect(reverse("view_reverse")) 17 #調用reverse()方法,參數爲urls.py中的url名稱,進行反向解析拿到"url_reverse/" 18 19 # return redirect("view_reverse") #redirect自帶了url反向解析,能夠不用重複調用reverse(),直接引用名稱
url標籤使用模板變量參數:url
urls.py:spa
url(r'^update/book_id=([0-9]+)', views.update,name="update"),code
views.pyorm
return render(request, "update.html", {"book":book_odj}) csrf
html:htm
<form action="{% url "update" book.id %}" method="post">