报以下这个错误的时候:django.template.exceptions.TemplateSyntaxError: ‘fliters’ is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
static
staticfiles
tz
需要在setting中注册
INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘booktest’,
’booktest.templatetags’, #注册这个前面是目录名称后面是创建的自定义过滤器文件夹
]
过程:先在目录下创建一个python包,名字叫做templatetags,注意名字不要错,然后自定一个过滤器Python文件,例如filter.py 这个名字任意。
#自定义过滤器
#过滤器就是python的函数
from django.template import Library
#创建一个Library类的对象
register =Library()
@register.filter
def mod(num):
‘’‘判断num是否为偶数’’’
return num%2 == 0
然后在html文件中加载
{% load filter%}
自定义过滤器至少有一个参数,最多有两个参数,第一个参数由竖线 | 前面的自动传过来,第二个参数是:后面的-------->
{% elif book.id|mod_val:3 %}