django實現日期分類效果


日期分類效果圖

實現功能:能夠按照月份進行分類,統計每個月份的文章數量,沒有文章的月份不顯示。點擊每欄可以鏈接的當月的文章列表。

每月文章列表可以使用django的通用視圖MonthArticleView,比較容易實現。日期分類需要自己模板的context。

(參考鏈接地址:http://www.butteredcat.org/article/23/)

 

 1 def month_list():
 2     articles = Article.objects.all()
 3     year_month = set()   #設置集合,無重復元素
 4     for a in articles:
 5         year_month.add((a.cre_date.year,a.cre_date.month))  #把每篇文章的年、月以元組形式添加到集合中
 6     counter = {}.fromkeys(year_month,0)  #以元組作為key,初始化字典
 7     for a in articles:
 8         counter[(a.cre_date.year,a.cre_date.month)]+=1  # 按年月統計文章數目
 9     year_month_number = []  #初始化列表
10     for key in counter:
11         year_month_number.append([key[0],key[1],counter[key]])  # 把字典轉化為(年,月,數目)元組為元素的列表
12     year_month_number.sort(reverse=True)  # 排序
13     return {'year_month_number':year_month_number}  #返回字典context

 

然后使用合並到原來context中。

 

 

 

每月文章顯示,使用django的通用視圖MonthArticleView。

from django.views.generic.dates import MonthArchiveView

from .models import Article
 1 class ArticleMonthArchiveView(MonthArchiveView):
 2     template_name = 'blog/main/index_by_month.html'
 3     queryset = Article.objects.all()
 4     date_field = "cre_date"
 5     paginate_by = 4
 6 
 7     def get_context_data(self, **kwargs):
 8         context = super(ArticleMonthArchiveView,self).get_context_data(**kwargs)
 9         context["categories"] = Category.objects.annotate(num_article = Count('article'))
10         context.update(month_list())  
11         return context

 


免責聲明!

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



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