您好,登錄后才能下訂單哦!
命名 URL:
test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試頁面</title> </head> <body> <p>測試頁面</p> <form action="/test/" method="post"> <input type="text" name="username" value=""> <input type="submit" name="提交"> </form> <a href="/json_test/" rel="external nofollow" >json 數據</a> </body> </html>
urls.py:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/', views.json_test), ]
如果 urls.py 中的 json_test/ 路徑發生改變,test.html 中的地址也要改
可以使用反向 url 解析,給 json_test/ 起一個別名
urls.py:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/', views.json_test, name="json"), # 給該 url 匹配命名為 json ]
test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試頁面</title> </head> <body> <p>測試頁面</p> <form action="/test/" method="post"> <input type="text" name="username" value=""> <input type="submit" name="提交"> </form> <a href="{% url 'json' %}" rel="external nofollow" >json 數據</a> </body> </html>
這時候如果修改 urls.py 中的 json_test/ 路徑,就不需要再去修改 test.html
反向解析 URL:
如果需要重定向這樣的路徑的話,可以在 views.py 中這樣寫:
from django.shortcuts import render, redirect from django.urls import reverse # json 測試 def json_test(request): hobby = ["Music", "Movie", "Basketball", "Reading"] from django.http import HttpResponse, JsonResponse return JsonResponse(hobby, safe=False) def test(request): return redirect(reverse("json")) # 通過 json 反向得到路徑 json_test/
訪問:http://127.0.0.1:8000/test/ 就變成訪問:http://127.0.0.1:8000/json_test/
如果 url 需要傳參數的話:
urls.py:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/(?P<id>[0-9]{2,4})/(?P<title>[a-zA-Z]+)/', views.json_test, name="json"), ]
test.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試頁面</title> </head> <body> <p>測試頁面</p> <form action="/test/" method="post"> <input type="text" name="username" value=""> <input type="submit" name="提交"> </form> <a href="{% url 'json' 12 'abcd' %}" rel="external nofollow" >json 數據</a> </body> </html>
訪問:http://127.0.0.1:8000/test/
點擊 “json 數據”
反向解析需要參數的話:
urls.py:
from django.conf.urls import url, include from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/(?P<id>[0-9]{2,4})/(?P<title>[a-zA-Z]+)/', views.json_test, name="json"), ]
views.py:
from django.shortcuts import HttpResponse, redirect from django.urls import reverse def json_test(request, id, title): print("id: ", id) print("title: ", title) return HttpResponse(id+"----"+title) def test(request): return redirect(reverse("json", kwargs={"id": 23, "title": "aaaa"}))
訪問:http://127.0.0.1:8000/test/
跳轉到了:http://127.0.0.1:8000/json_test/23/aaaa/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。