Django實(shí)戰(zhàn):搭建個(gè)人博客(四)
[TOC]
開發(fā)文章詳情頁
1. URL綁定
在blog/url.py
中添加detail視圖函數(shù)的匹配規(guī)則:
urlpatterns = [
path('', views.index, name='index'),
# pk會(huì)作為第二個(gè)參數(shù)傳給detail視圖函數(shù)速警,其中第一個(gè)參數(shù)是request
# <int:pk>,<string:st>等是Django的路由寫法
path('post/<int:pk>',views.detail,name='detail')
]
2. detail視圖函數(shù)
在views.py
中添加如下磷账,其中get_object_or_404
方法可以按主鍵查詢數(shù)據(jù)庫中的數(shù)據(jù)猜惋,不存在則返回404 response惩淳。
from django.shortcuts import render,get_object_or_404
def detail(request,pk):
post=get_object_or_404(Post,pk=pk)
return render(request,'blog/detail.html',context={
'post':post
})
為Post模型定義get_absolute_url
方法:
def get_absolute_url(self):
# reverse函數(shù)找到blog應(yīng)用的urlpatterns中谊娇,名為detail的url哆键,并傳入kwargs中的參數(shù)力九,返回這個(gè)url
# 通過這種解析url的方式娜扇,使得url與視圖函數(shù)的綁定更加靈活,實(shí)現(xiàn)了url與模型實(shí)例的關(guān)聯(lián)
return reverse('blog:detail', kwargs={'pk': self.pk})
3. 模板繼承的使用方法
由于文章詳情頁與文章目錄頁大部分內(nèi)容相同毁枯,因此采用模板繼承的方式慈缔。
在templates/目錄下新建一個(gè)base.html,其中嵌入如下結(jié)構(gòu):
<main class="col-md-8">
{% block main %}
{% endblock %}
</main>
<aside class="col-md-4">
{% block aside %}
{% endblock %}
</aside>
在templates/blog/detail.html中,首部通過{%extends 'base.html'%}
語句表明繼承關(guān)系种玛,再寫block內(nèi)部的細(xì)節(jié)
{%extends 'base.html'%}
{%block main%}
# 此處填寫main標(biāo)簽里的細(xì)節(jié),例如:
<body>
<h1 class="entry-title">{{post.title}}</h1> # post由detail視圖函數(shù)傳遞給模板
</body>
{%end block%}
{%block aside%}
# 此處編寫aside標(biāo)簽(側(cè)邊欄相關(guān)的內(nèi)容)的細(xì)節(jié)
{%end block%}
通過這種方式可以實(shí)現(xiàn)模板繼承藐鹤,類似于子模板detail.html覆寫了父模板base.html中block包裹的部分。
4. 從目錄頁到詳情頁的跳轉(zhuǎn)
在index.html的文章標(biāo)題和“繼續(xù)閱讀”處調(diào)用剛才定義的{{ post.get_absolute_url }}
模板變量赂韵,獲取所點(diǎn)擊文章的url(模板變量不僅可以是模型的屬性娱节,也可以是一個(gè)可調(diào)用的方法)
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
<a href="{{ post.get_absolute_url }}" class="more-link">繼續(xù)閱讀 <span class="meta-nav">→</span></a>
5. 詳情頁內(nèi)容的填充
通過模板變量對(duì)模板進(jìn)行填充,以正文body為例:
<div class="entry-content clearfix">
{{ post.body }}
</div>
知識(shí)點(diǎn)總結(jié)
- 視圖函數(shù)
- 模板繼承
- 逆向解析文章的url
接下來開發(fā)側(cè)邊欄的內(nèi)容祭示。