橡皮擦,一個逗趣的互聯網高級網蟲,新的系列,讓我們一起進入 Django 世界,
已經完成的文章
- 滾雪球學 Python 第三輪,Python Web 之 Django 的世界
- 小手哆嗦一下,就能用 Python Django 實作一個微型博客系統
- Django 做個小后臺,細節在完善一點點,滾雪球學 Python 第三階段
- Django QuerySet 就學那么一點點,一點點就夠了
- 看完這篇博客,Python Django 你就學會一半了
- 讓我們一起開發【菜譜系統】吧,滾雪球學 Python 第三輪專案計劃
- 出現吧,Python Web 菜譜系統的首頁,不會前端技術,也能做
- 簡簡單單實作 Python Web 的登錄注冊頁面,還包含一半邏輯,
- Python Web 菜譜專案再次前進一步,從應用層了解內置用戶認證系統
- 菜譜系統小成階段,Python Web 領域終于攻占一個小山頭
- 銷售 小姐姐 給買家打分系統,用 Python Django 又整了一個花活
- 幫小姐姐打分系統的模型創建,滾雪球學 Python 第三輪第 12 篇
滾雪球學 Python 第三輪
- 已經完成的文章
- 十三、視圖與模板
- 13.1 打分系統的視圖
- 13.2 重拾模板
- 13.3 本篇博客小節
十三、視圖與模板
第十二篇博客已經初步構建好了后臺管理頁面,接下來繼續對 Django 的視圖與模板進行學習,
13.1 打分系統的視圖
Django 中每一個頁面都是通過視圖進行展示的,而視圖背后對應的都是 Python 中的函式或者類中的方法,在 Django 中通過 URLconfs 進行視圖匹配,這里涉及一個新的概念,叫做 URL 模式字串,對應的瀏覽器地址欄里面的 /aaa/bbb/ccc 這類內容,
在 scoring/views.py 檔案中添加如下代碼,分別是 3 個視圖,其中部分資料為測驗用資料,
# 打分系統首頁
def index(request):
return HttpResponse("小姐姐打分系統")
# 客戶詳情&打分頁面
def detail(request, _id):
return HttpResponse(f"客戶ID為{_id}")
# 客戶分數查閱
def show_score(request, _id):
totle = 0
return HttpResponse(f"客戶 {_id} 的總分是 {totle}")
views.py 檔案中的內容添加完畢,即可修改 scoring/urls.py 中的 URL 模式字串了,具體如下:
urlpatterns = [
path("", views.index, name="index"),
path("<int:_id>/", views.detail, name="detail"),
path("<int:_id>/score", views.show_score, name="show_score"),
]
此時還需要關注的一個檔案是 settings.py,在該檔案中存在一個配置項如下:
ROOT_URLCONF = 'cutegirl.urls'
上述配置項決定了當用戶訪問的 URL 攜帶 scoring 時,Django 會自動跳轉到 scoring.urls 中進行匹配,
現在可以通過訪問下述地址獲取不同的展示結果了,
http://127.0.0.1:8000/scoring/2/
http://127.0.0.1:8000/scoring/2/score
代碼中 <int:_id> 在后續博客中會補充相應的說明,基本含義是前面是資料型別,后面是視圖的引數名,
13.2 重拾模板
在 scoring 目錄下新建一個目錄叫做 templates ,然后在 templates 中再創建一個檔案夾 ttt,這個檔案名可以任意,甚至可以創建多套模板都沒有問題,
在撰寫代碼前,先通過命令列向 sqlite 中輸入一些資料,
> python manage.py shell
>>> from scoring.models import Customer
>>> cus = Customer(1,"橡皮擦",15012345678)
>>> cus.save()
>>> cus = Customer(2,"1_bit",15066667777)
>>> cus.save()
資料準備完畢,可以通過下述代碼輸出資料進行基礎測驗,查看視圖與模型之間的關聯關系是否打通,
修改 views.py 檔案,填入下述內容代碼,
from django.http import HttpResponse
from .models import Customer
# 打分系統首頁
def index(request):
customers = Customer.objects.all()
ret = ",".join([c.name for c in customers])
return HttpResponse(ret)
此時訪問 http://127.0.0.1:8000/scoring/,得到如下內容,

接下來配合視圖在對 views.py 中的內容進行修改,
from django.http import HttpResponse
from .models import Customer
from django.template import loader
# 打分系統首頁
def index(request):
customers = Customer.objects.all()
template = loader.get_template("ttt/index.html")
context = {
"customers": customers
}
return HttpResponse(template.render(context, request))
上述代碼中,優先匯入了模型類與 template 中的 loader 模塊,然后修改 index 函式,通過 Customer.objects.all() 獲取之前錄入的客戶資料,
template = loader.get_template("ttt/index.html") 用于加載模板,最后將資料通過 context 傳遞到 index.html 頁面中,
此時修改一下 index.html 頁面邏輯,內容如下:
{% if customers %}
<ul>
{% for c in customers %}
<li><a href="/scoring/{{ c._id }}">{{ c.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>無客戶</p>
{% endif %}
重繪頁面,出現如下 BUG,原因是 c._id 導致,因 _ 開頭的變數在模板中被當做私有變數,
TemplateSyntaxError at /scoring/ Variables and attributes may not begin with
underscores: 'c._id'
解決辦法涉及新的模板標簽知識點,
在 scoring 目錄中新建立一個 templatetags 檔案夾,其中創建兩個檔案 __init__.py 與 getid.py,目錄結構如下:

__init__.py 保持為空即可,getid.py 中增加如下代碼,這里相當于在 Django 模板中手動創建了一個過濾器,順便再回顧一下 Django 模板語法,
- 變數:兩個大括號括起來的
{{變數名}}; - 標簽:代碼段
{% 代碼塊 %}; - 過濾器:豎線(
|); - 注釋:
{# 這里是注釋 #},
from django import template
register = template.Library()
@register.filter(name='getid')
def getid(d):
return d._id
完成準備作業之后,修改 index.html 檔案,
{% load getid %} {% if customers %}
<ul>
{% for c in customers %}
<li><a href="/scoring/{{ c|getid }}">{{ c.name }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>無客戶</p>
{% endif %}
再次運行代碼,得到的頁面原始碼如下:
<ul>
<li><a href="/scoring/1">橡皮擦</a></li>
<li><a href="/scoring/2">1_bit</a></li>
</ul>
views.py 代碼中的函式會回傳一個 HttpResponse 物件到瀏覽器,該處理邏輯經常使用,所以 Django 提供了一個內置好的簡寫函式,render ,
from django.shortcuts import render
# 打分系統首頁
def index(request):
customers = Customer.objects.all()
context = {
"customers": customers
}
return render(request, "ttt/index.html", context)
剛才已經提及了 Django 模板系統中的常見語法,對于模板系統還有如下內容需要補充,
修改模板中的超鏈接生成方式,在前文中使用字串拼接的方式 <a href="/scoring/{{ c|getid }}">{{ c.name }}</a> 生成了一個超鏈接,該內容可以進行優化,在 scoring/urls.py 中,我們給每個 URL 模式都進行了命名,
urlpatterns = [
path("", views.index, name="index"),
path("<int:id>/", views.detail, name="detail"),
path("<int:id>/score", views.show_score, name="show_score"),
]
通過上述命名,可以修改模板中超鏈接的生成方式為:
{% for c in customers %}
<li><a href="{% url 'detail' c|getid%}">{{ c.name }}</a></li>
{% endfor %}
在 Django 中任何功能都是以應用形式存在的,即會出現多個應用在一個專案內的場景,此時 URL 模式可能會出現相同內容,解決辦法非常簡單,通過在 urls.py 檔案中增加 app_name 變數設定 URLconf 的命名空間,
from django.urls import path
from . import views
app_name = "scoring"
urlpatterns = [
path("", views.index, name="index"),
path("<int:id>/", views.detail, name="detail"),
path("<int:id>/score", views.show_score, name="show_score"),
]
命名名稱空間之后,就可以在 index.html 檔案中增加名稱空間相關資料,
{% for c in customers %}
<li><a href="{% url 'scoring:detail' c|getid%}">{{ c.name }}</a></li>
{% endfor %}
13.3 本篇博客小節
本篇我們再次對打分系統中的視圖與模板進行了補充與學習,一起打卡吧,
相關閱讀
- Python 爬蟲 100 例教程,超棒的爬蟲教程,立即訂閱吧
- Python 游戲世界(更新中,目標文章數 50+,現在訂閱,都是老粉)
- Python 爬蟲小課,精彩 9 講
今天是持續寫作的第 131 / 200 天,
如果你想跟博主建立親密關系,可以關注同名公眾號 夢想橡皮擦,近距離接觸一個逗趣的互聯網高級網蟲,
博主 ID:夢想橡皮擦,希望大家點贊、評論、收藏,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/274446.html
標籤:其他
