首页 > 其他 > 详细

django 添加自定义context

时间:2016-05-29 18:11:19      阅读:158      评论:0      收藏:0      [点我收藏+]

文档参考;http://python.usyiyi.cn/django_182/ref/templates/api.html

添加自定义上下文文件custom_processors.py

 1 # coding=utf-8
 2 
 3 from .models import Article,Category
 4 from django.db.models import Count
 5 
 6 def month_list(request):
 7     articles = Article.objects.all()
 8     year_month = set()
 9     for a in articles:
10         year_month.add((a.cre_date.year,a.cre_date.month))
11     counter = {}.fromkeys(year_month,0)
12     for a in articles:
13         counter[(a.cre_date.year,a.cre_date.month)]+=1
14     year_month_number = []
15     for key in counter:
16         year_month_number.append([key[0],key[1],counter[key]])
17     year_month_number.sort(reverse=True)
18     return {year_month_number: year_month_number}
19 
20 def category(request):
21     category = Category.objects.annotate(num_article=Count(article))
22     return {"categories": category}

 

更在setting.py文件

 1 TEMPLATES = [
 2     {
 3         BACKEND: django.template.backends.django.DjangoTemplates,
 4         DIRS: [],
 5         APP_DIRS: True,
 6         OPTIONS: {
 7             context_processors: [
 8                 django.template.context_processors.debug,
 9                 django.template.context_processors.request,
10                 django.contrib.auth.context_processors.auth,
11                 django.contrib.messages.context_processors.messages,
12                 blog.custom_processors.month_list,
13                 blog.custom_processors.category
14             ],
15         },
16     },
17 ]

 

可以在前端使用year_month_number和categories

 

django 添加自定义context

原文:http://www.cnblogs.com/hb91/p/5539796.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!