django自定义过滤器的步骤

1.必须存在于一个应用内,并且应用必须包含在INSTALLED_APPS中
2.必须包含一个templatetags文件夹,和models.py、views.py一个目录级别。其中必须有__init__.py文件


3.新建的标签或者过滤器必须以module的形式存在于templatetags文件夹中。module文件的名字就是你在

template中装载的tags。所以不要和其他app中的标签或者过滤器冲突。

例子:
文件目录如下:
polls/
     models.py
     templatetags/
          __init__.py
          cut.py
     views.py

在template可以这样使用自定义的标签:
{% load poll_extras %}

4.打开tag或者filter的文件,输入:
from django import template
register=template.Library()
def cut(value):
    return value=='abc'
register.filter('cut',cut)
'cut'是过滤器的名字
cut是处理函数
或者
@register.filter(name='cut')
def lower(value):
   return value>'abc'
如果不写name参数,则django会使用函数的名字代替。

完整程序:

cut.py:

from django import  template
register=template.Library()
def cut(value):
    return 'abc'
register.filter('cut',cut)


index.py:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
{% load cut %}
 {% for p in Person %}
     {{ p|cut }}
{% endfor %}
</body>
</html>


ok!

原文地址:https://www.cnblogs.com/chenjianhong/p/4145088.html