table of Contents
inclusion_tag module
1. When a piece of content area of the page to be presented for use on multiple pages, and the contents of the region need to pass parameters to display properly, then we can prioritize inclusion_tag modules:
Custom label filter inclusion_tag three-step strategy:
1. In the application must create a new folder named templatetags
2. py files in any folder under a new name
3. You must write two codes within the py file
from django.template import Library
register = Library
2. Let's look at an example of a BBS
from django.template import Library
from app01 import models
from django.db.models import Count
from django.db.models.functions import TruncMonth
register = Library()
@register.inclusion_tag('left_menu.html')
# 定义一个函数,接收一个username参数,(因为调用这个的时候需要传一个username参数)
def my_menu(username):
user_obj = models.Userinfo.objects.filter(username=username).first()
# 因为用户表与blog表示一对一的关系表所以可以通过下面的方法取值
blog = user_obj.blog
# 1.查询当前用户每一个分类及分类下的文章数
category_list = models.Categroy.objects.filter(blog=blog).annotate(num=Count('article')).values_list('num', 'cate_name','pk')
# 2.查询当前用户每一个标签及标签下的文章数
tag_list = models.Tag.objects.filter(blog=blog).annotate(num=Count('article')).values_list('tag_name', 'num', 'pk')
# 3.按年月分组
data_list = models.Article.objects.filter(blog=blog).annotate(month=TruncMonth('create_time')).values('month').annotate(num=Count('pk')).values_list('month', 'num')
return locals()