django 添加自定义context
文档参考;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