Django自定义过滤器定义与用法示例
作者:水痕01 时间:2022-07-24 13:09:00
本文实例讲述了Django自定义过滤器定义与用法。分享给大家供大家参考,具体如下:
一、自定义过滤器的介绍
前面我们就介绍过过滤器其实就是一个函数,把要过来的字段传递到一个函数内,进行加工处理,返回一个新的值展现在页面中,在实际开发中系统自带的过滤器有时候不能满足我们的需求的时候就要自定义
二、Django中自定义过滤器有两种方式
1、在组件(App)中的templatetags
创建一个单独的py文件
2、单独创建一个组件(App)用来存放项目中所有的自定义过滤器
三、在项目中的组件中创建自定义过滤器
1、只能在安装的组件(App
)中
2、只能在组件(App)下的templatetags
包内创建
3、必须使用修饰器@register.filter
4、定义一个方法,传递值进去进行处理,返回新的值
5、创建自定义过滤器
①. 在templatetags包下创建一个poll.py的文件
from django import template
register = template.Library()
@register.filter
def mycut(value,args):
return value.replace(args,"")
6、 使用自定义过滤器
①. 先引入文件{% load poll %}
②. 使用
{% load poll %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>{{ msg | mycut:' '}}</p>
</body>
</html>
四、可以自定义一个组件(App
)[由于不需要太多的文件,就手动创建一个]
1、手动创建一个包
2、在包中创建一个templatetags
的包
3、将创建的这个包在settings.py
中注入
4、在templatetags
中创建文件及函数
5、过滤器的使用(跟上面一样的)
五、补充说明
如果是对字符串操作的一般都会引入@stringfilter
修饰符
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
def mycut(value,args):
return value.replace(args,"")
@register.filter
@stringfilter
def mylower(value):
return value.lower()
希望本文所述对大家Django框架的Python程序设计有所帮助。
来源:http://blog.csdn.net/kuangshp128/article/details/75727926
标签:Django,自定义过滤器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ASP中SESSION无法保存问题的解决办法
2023-06-27 15:40:12
![](https://img.aspxhome.com/file/UploadPic/201211/30/20121130203846956s.jpg)
numpy的squeeze函数使用方法
2022-04-15 10:02:07
![](https://img.aspxhome.com/file/2023/3/75083_0s.png)
python环形单链表的约瑟夫问题详解
2023-03-02 04:13:10
python3.7 使用pymssql往sqlserver插入数据的方法
2021-10-13 00:23:34
一份ASP内存的释放的实验报告
2007-10-17 13:09:00
![](https://img.aspxhome.com/file/UploadPic/200710/17/2007101713177321s.gif)
PyTorch详解经典网络ResNet实现流程
2022-08-06 09:40:32
![](https://img.aspxhome.com/file/2023/7/101587_0s.png)
Python利用matplotlib生成图片背景及图例透明的效果
2023-08-22 08:35:18
![](https://img.aspxhome.com/file/2023/1/110271_0s.jpg)
Python网络爬虫实例讲解
2023-09-11 23:18:10
![](https://img.aspxhome.com/file/2023/5/77575_0s.jpg)
Python找出微信上删除你好友的人脚本写法
2023-11-09 15:55:58
简单了解Python字典copy与赋值的区别
2022-07-16 11:35:52
PHP预定义变量9大超全局数组用法详解
2023-06-14 10:23:47
页面中图像格式的选用之我见
2007-10-31 18:11:00
![](https://img.aspxhome.com/file/UploadPic/200710/31/2007103119144423s.png)
利用python控制Autocad:pyautocad方式
2023-08-03 00:05:20
![](https://img.aspxhome.com/file/2023/8/99278_0s.jpg)
Python中处理字符串之endswith()方法的使用简介
2023-02-25 09:05:36
详解python中index()、find()方法
2021-02-25 02:38:59
![](https://img.aspxhome.com/file/2023/6/100956_0s.png)
Pytorch转tflite方式
2023-08-10 03:47:29
python爬取淘宝商品销量信息
2023-06-01 14:59:03
Python 程序报错崩溃后如何倒回到崩溃的位置(推荐)
2021-01-08 16:14:34
![](https://img.aspxhome.com/file/2023/1/83991_0s.jpg)
python pandas 时间日期的处理实现
2021-09-05 02:38:07
![](https://img.aspxhome.com/file/2023/9/115009_0s.png)
python贪吃蛇游戏代码
2023-07-22 04:19:17
![](https://img.aspxhome.com/file/2023/3/60493_0s.jpg)