這一節(jié)依然是實(shí)現(xiàn)一些小功能:readmore和搜索功能。
readmore就是在列表顯示文章時(shí)只顯示開(kāi)頭的小部分正文,通過(guò)readmore按鈕進(jìn)入詳情頁(yè)才能閱讀全文。
理想的搜索功能應(yīng)該是可以在全文中搜索關(guān)鍵字,更人性化的設(shè)計(jì)是在搜索結(jié)果界面的文章中高亮關(guān)鍵字。根據(jù)教程 全文搜索 ,我雖然也實(shí)現(xiàn)了全文搜索,但對(duì)此的理解還不深,界面也沒(méi)有美化,因此暫時(shí)先用閹割功能的 標(biāo)題搜索 ,即只在標(biāo)題中搜索關(guān)鍵字。
ReadMore
Readmore就是文字截?cái)嗪鸵粋€(gè)鏈接按鈕的組合。
在post_list.html把正文text用truncatewords過(guò)濾器過(guò)濾,然后在正文下面添加一個(gè)進(jìn)入詳情頁(yè)的按鈕:
<p>{{ post.text|linebreaks|truncatewords:5 }}</p>
<a class="pure-button" href="{% url 'post_detail' pk=post.pk %}">Read More >>> </a>
truncatewords后面的數(shù)字5指示過(guò)濾器大小,另外還有truncatechars、slice等過(guò)濾器也可以實(shí)現(xiàn)類(lèi)似效果。讀者可以改變數(shù)字和過(guò)濾器體會(huì)他們的不同。
搜索功能
這里實(shí)現(xiàn)的是比較簡(jiǎn)單的按標(biāo)題搜索。
在base.html的按鈕后增加一個(gè)文本框:
<li>
<form class="pure-form" action="/search/" method="get">
<input class="pure-input-3-3" type="text" name="s" placeholder="search"></form>
</li>
注意這里name="s"用s命名輸入文字。
然后在views.py添加視圖邏輯:
def blog_search(request):
if 's' in request.GET:
s = request.GET['s']
if not s:
return render(request,'blog/post_list.html')
else:
post_list = Article.objects.filter(title__icontains = s)
if len(post_list) == 0 :
return render(request, 'blog/search.html', {'post_list': post_list, 'error': True})
else:
return render(request, 'blog/search.html', {'post_list': post_list, 'error': False})
return redirect('/')
這里的查詢(xún)就是以s為關(guān)鍵字進(jìn)行查詢(xún)的。
查詢(xún)結(jié)果顯示在blog/search.html,所以新建這個(gè)模板:
{% extends "blog/base.html" %}
{% block content %}
<div class="posts">
{% if error %}
<h2 class="post-title">沒(méi)有相關(guān)文章題目</h2>
{% else %}
{% for post in post_list %}
<div class="date">
{% if post.published_date %}
{{ post.published_date |date:'M d, Y'}}
{% endif %}
</div>
<h3><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h3>
<p>
<a class="post-category post-category-js" href="{% url 'search_tag' tag=post.category %}"><span class="glyphicon glyphicon-tag"></span>{{ post.category|title }}</a>
</p>
<p>{{ post.text|linebreaks|truncatewords:5 }}</p>
<a class="pure-button" href="{% url 'post_detail' pk=post.pk %}">Read More >>> </a>
{% endfor %}
{% endif %}
</div>
{% endblock %}
注意由于模板內(nèi)有漢字,因此要用utf-8編碼以免亂碼??梢杂肞yCharm設(shè)置編碼格式,也可以用代碼說(shuō)明。
最后urls.py里面增加一條url:
url(r'^search/$', views.blog_search, name='search'),
刷新頁(yè)面搜索試試。
2016.10.26