django模板之方向解析:根據url生成鏈接地址

環境同上一篇django文章。


運行django的web服務:

 cd py3/django-test1/test4
 python manage.py runserver 192.168.255.70:8000


先演示下,在html中使用a標籤超鏈接,自動匹配到應用的url路由,再展示指定的html頁面:

編輯視圖函數:

vim bookshop/views.py

from django.shortcuts import render
from .models import *
def index(request):
    #list = HeroInfo.objects.all()
    list = HeroInfo.objects.filter(isDelete=False)
    context = {'list1':list}
    return render(request,'bookshop/index.html',context)
def show(request,id):
    context = {'id':id}
    return render(request,'bookshop/show.html',context)

編輯url路由:

vim bookshop/urls.py

from django.conf.urls import url
from .  import views

urlpatterns = [
    url(r'^$',views.index,name='index'),
    
    url(r'^(\d+)$',views.show,name='show'),
    #小括號表示要在url中傳遞參數;
]

編輯html模板:

vim templates/bookshop/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="123">鏈接數字</a>
</body>
</html>

vim templates/bookshop/show.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ id }}
</body>
</html>

瀏覽器訪問:http://192.168.255.70:8000/

顯示:

QQ截圖20181205005207.png

點擊超鏈接:瀏覽器地址自動變爲:http://192.168.255.70:8000/123

顯示:

QQ截圖20181205005309.png


當主url路由test4/urls.py修改爲:

urlpatterns = [
    ...
    url(r'^bookshop/',include('bookshop.urls',namespace='bookshop')),
]

這樣,在更改url路由時,就需要更改html中的鏈接地址;如果使用django中的反向解析來,在更改url路由同時,不需要在html中修改鏈接地址,反向解析會自動完成修改:


編輯html模板:

vim templates/bookshop/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--<a href="123">鏈接數字</a>-->
<a href="{% url 'bookshop:show' '123' %}">鏈接--反向解析</a>
<!--bookshop是主url路由中的namespace屬性,show是應用的url路由中的name屬性,123則是應用url中要接收的參數-->
</body>
</html>

僅修改html模板文件的反向解析部分,其它配置不變。

瀏瀏覽器訪問同上。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章