Fork me on GitHub

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%}

 

posted @ 2016-06-14 17:24  洋葱源码  阅读(3276)  评论(0编辑  收藏  举报