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

 

posted @ 2016-05-29 11:07  hb91  阅读(3026)  评论(0编辑  收藏  举报