django博客功能實現——標簽功能


標簽功能添加流程

0.功能概括

標簽作為文章中的分類標記,會顯示出該文章是關於哪一方面的文章,比如是關於python的還是關於django的。

當我們點擊該標簽的時候,會出現該博客中所有屬於該標簽的文章

1.在其他頁面做一個鏈接,指向標簽分類頁面

在其他頁面中顯示該文章標簽的地方操作,對該標簽添加一個URL,作用是定向到分類標簽頁面的URL(例如tag頁面)

 <a href="{% url "search_tag" tag=post.category %}">{{post.category}}</a>  

連接進入name為search_tag的URL,並將選中的標簽(post.category)賦值給tag,一同傳遞給下一個頁面

2.定義一個URL,既定義標簽分類頁面的網址

上一步中,我們指向了一個新的URL,在這里定義出這個URL: 

 url(r'^tag(?P<tag>\w+)/$','article.views.search_tag',name='search_tag'), 

url接受上一步中傳進來的tag值,並放在http中傳遞給視圖函數。

3.在views中調用屬於同一個標簽文章

1 def search_tag(request,tag): #tag在URL中獲取
2     try:
3         post_list = Article.objects.filter(category__iexact=tag) #對文章進行過濾,過濾方法是:標簽不區分大小寫,並且等於tag
4         raise Http404
5     return render(request,'tag.html',{'post_list':post_list})

該視圖中過濾獲取所需要的文章,並調用tag.html,讓其在該html中顯示

4.定義html,用來做顯示輸出

 1 {% block content %}
 2 <div class="posts">
 3     {% for post in post_list %}
 4         <section class="post">
 5             <header class="post-header">
 6 
 7             <h2 class="post-title"><a href="{% url "detail" id=post.id %}">{{post.title}}</a></h2>
 8 
 9                 <p class="post.meta">
10                    Time: <a class="post-author" href="#">{{post.date_tiem|date:"Y M d"}}
11                    </a><a class="post-category post-category-js" href="{% url "archives" tag=post.category %}">{{post.category|title}}</a>
12                 </p>
13             </header>
14 
15                 <div class="post-description">
16                      <p>
17                          {{post.content|custom_markdown}}
18                      </p>
19                 </div>
20                 <a class="pure-button" href="{% url "detail" id=post.id %}">閱讀更多>>></a>
21 
22         </section>
23     {% endfor%}
24 </div>
25 {%endblock%}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM