您的位置:首页 > 编程语言 > Go语言

django实现日期分类效果

2016-05-29 11:07 411 查看
日期分类效果图



实现功能:能够按照月份进行分类,统计每个月份的文章数量,没有文章的月份不显示。点击每栏可以链接的当月的文章列表。

每月文章列表可以使用django的通用视图MonthArticleView,比较容易实现。日期分类需要自己模板的context。

(参考链接地址:http://www.butteredcat.org/article/23/)

def month_list():
articles = Article.objects.all()
year_month = set()   #设置集合,无重复元素
for a in articles:
year_month.add((a.cre_date.year,a.cre_date.month))  #把每篇文章的年、月以元组形式添加到集合中
counter = {}.fromkeys(year_month,0)  #以元组作为key,初始化字典
for a in articles:
counter[(a.cre_date.year,a.cre_date.month)]+=1  # 按年月统计文章数目
year_month_number = []  #初始化列表
for key in counter:
year_month_number.append([key[0],key[1],counter[key]])  # 把字典转化为(年,月,数目)元组为元素的列表
year_month_number.sort(reverse=True)  # 排序
return {'year_month_number':year_month_number}  #返回字典context


然后使用合并到原来context中。

每月文章显示,使用django的通用视图MonthArticleView。

from django.views.generic.dates import MonthArchiveView

from .models import Article


class ArticleMonthArchiveView(MonthArchiveView):
template_name = 'blog/main/index_by_month.html'
queryset = Article.objects.all()
date_field = "cre_date"
paginate_by = 4

def get_context_data(self, **kwargs):
context = super(ArticleMonthArchiveView,self).get_context_data(**kwargs)
context["categories"] = Category.objects.annotate(num_article = Count('article'))
context.update(month_list())
return context
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: