在Django中自定义filter并在template中的使用详解
作者:LiveMost 发布时间:2021-01-15 19:17:45
标签:Django,自定义,filter,template
Django内置的filter有很多,然而我们由于业务逻辑的特殊要求,有时候仍然会不够用,这个时候就需要我们自定义filter来实现相应的内容。接下来让我们从自定义一个get_range(value)来产生列表的filter开始吧。
首先在你的django app的models.py的同级目录建立一个templatetags的文件夹,并在里面新建一个init.py的空文件,这个文件确保了这个文件夹被当做一个python的包。在添加了templatetags模块之后,我们需要重新启动服务器才能使其有效。
polls/
__init__.py
models.py
templatetags/
__init__.py
views.py
然后在templatetags中新建一个python文件,文件名就是以后需要加载到页面的自定义库的名字。在这里我们新建一个generalfilters.py文件。
polls/
__init__.py
models.py
templatetags/
__init__.py
generalfilters.py
views.py
为了让库生效,必须在文件里添加一个模块级别的register变量。它是template.Library的实例,确保了标签和过滤器的有效性。
编辑generalfilters.py,添加
from django import template
register=template.Library()
@register.filter
def get_range(value):
return range(value)
上述代码中定义了一个生成列表的函数,@register.filter表示这个函数是一个过滤器。至此我们的生成列表的过滤器就已经写好了。接下来我们需要把这个过滤器的库加载到模板里。
在你想要使用的模板的顶部加上{% load generalfilters %},就可以使用这个过滤器了。
{% for i in 5|get_range_bet_within %}
{{i}}
{% endfor %}
运行结果
补充知识:Django 自定义筛选器:重写DateFieldListFilter
我就废话不多说了,大家还是直接看代码吧!
class MyDateTimeFilter(admin.filters.DateFieldListFilter):
def __init__(self, *args, **kwargs):
super(MyDateTimeFilter, self).__init__(*args, **kwargs)
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
filter_end_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
filter_start_date_for_one_week = filter_end_date - datetime.timedelta(days=7)
month_with_day31 = [1,3,5,7,8,10,12]
if filter_end_date.month in month_with_day31 and filter_end_date.day == 31 and filter_end_date.month != 3:
if filter_end_date.month == 1:
filter_start_date_for_one_month = filter_end_date.replace(year=filter_end_date.year-1, month=12)
else:
filter_start_date_for_one_month = filter_end_date.replace(month=filter_end_date.month-1, day=30)
elif filter_end_date.month == 3 and filter_end_date.day in [29, 30, 31]:
if is_leap_year(filter_end_date.year):
filter_start_date_for_one_month = filter_end_date.replace(month=filter_end_date.month-1, day=29)
else:
filter_start_date_for_one_month = filter_end_date.replace(month=filter_end_date.month-1, day=28)
else:
if filter_end_date.month == 1:
filter_start_date_for_one_month = filter_end_date.replace(year=filter_end_date.year-1, month=12)
else:
filter_start_date_for_one_month = filter_end_date.replace(month=filter_end_date.month-1)
filter_start_date_for_six_month = ''
filter_start_date_for_six_month_month = (filter_end_date.month - 6 + 12) % 12
if filter_start_date_for_six_month_month == 0:
filter_start_date_for_six_month_month = 12
if filter_start_date_for_six_month_month in month_with_day31:
if filter_end_date.month > 6:
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month)
else:
filter_start_date_for_six_month = filter_end_date.replace(year=filter_end_date.year-1, month=filter_start_date_for_six_month_month)
elif filter_start_date_for_six_month_month == 2:
if filter_end_date.day in [29, 30, 31]:
if is_leap_year(filter_end_date.year):
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month, day=29)
else:
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month, day=28)
else:
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month)
else:
if filter_end_date.day == 31 and filter_end_date.month >6:
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month, day=30)
elif filter_end_date.day == 31 and filter_end_date.month <=6:
filter_start_date_for_six_month = filter_end_date.replace(year=filter_end_date.year-1, month=filter_start_date_for_six_month_month, day=30)
elif filter_end_date.day <31 and filter_end_date.month >6:
filter_start_date_for_six_month = filter_end_date.replace(month=filter_start_date_for_six_month_month)
else:
filter_start_date_for_six_month = filter_end_date.replace(year=filter_end_date.year-1, month=filter_start_date_for_six_month_month)
filter_end_date = filter_end_date + datetime.timedelta(days=1)
self.links = ((
('------', {}),
('Past week', {
self.lookup_kwarg_since: str(filter_start_date_for_one_week),
self.lookup_kwarg_until: str(filter_end_date),
}),
('Past month', {
self.lookup_kwarg_since: str(filter_start_date_for_one_month),
self.lookup_kwarg_until: str(filter_end_date),
}),
('Past 6 months', {
self.lookup_kwarg_since: str(filter_start_date_for_six_month),
self.lookup_kwarg_until: str(filter_end_date),
}),
('All', {}),
))
来源:https://blog.csdn.net/l497626363/article/details/78659921


猜你喜欢
- 网上看到一个python写的数独,很好玩,分享给大家。import randomimport itertoolsfrom copy impo
- 备注 与 DELETE 语句相比,TRUNCATE TABLE 具有以下优点: 所用的事务日志空间较少。 DELETE 语句每次删除一行,并
- 通过Python中的matplotlib绘制百分比堆叠柱状图,并为每一个类别设置不同的填充图案。主要原因是有些论文打印出是黑白色的,不同类别
- 前言不管是哪门语言,千变万化不离其宗,深入理解其本质,方能应用自如。对应到js,闭包,原型,函数,对象等是需要花费大功夫思考、理解的。本文穿
- 不同的开发工具,都能俘获各自的一批忠实的用户和支持者。VS Code、Eclipse、IDEA、atom....到底哪一款开发工具更好?一直
- 安装pyqt5和pyqt5-tools利用pyqt5编写GUI界面,首先需要下载pyqt5以及相应的pyqt5-tools,我的python
- 如何使用MsChart?MsChart是微软出品的一款功能强大的制作图表工具,用它可以很方便的建立各种图表。下面我们举例来说明:submit
- 步骤:1、新建一个空文件,文件名为hhhh2、初始化git init3、自己要与origin master建立连接(下划线为远程仓库链接)g
- 我在初学时查阅过大量相关资料,发现其中提供的很多方法实际操作起来并不是那么回事。对于简单的应用,这些资料也许是有帮助的,但仅限于此,因为它们
- 效果展示 准备工作1.canvas的使用主要用到了 bindtouchstart , bindtouchmove 两个属性,捕捉手
- 有时候我们需要使用python执行一些脚本,可能需要让程序自动按键或自动点击鼠标,下面的代码实现了对键盘的模拟按键,需要安装pypiwin3
- 在上一篇文章中,我整理了pandas在数据合并和重塑中常用到的concat方法的使用说明。在这里,将接着介绍pandas中也常常用到的joi
- PyQt5安装 在cmd下输入pip install PyQt5 完成PyQt5安装,安装完成后,在python安装目录下可以看到配置PyC
- sql脚本是包含一到多个sql命令的sql语句,我们可以将这些sql脚本放在一个文本文件中(我们称之为“sql脚本文件”),然后通过相关的命
- 本文介绍了Python中Selenium模拟JQuery滑动解锁实例,分享给大家,也给自己留个笔记滑动解锁一直做UI自动化的难点之一,我补一
- 背景在微信分享开发的时候我们通常的流程是 <?php require_once "jssdk.php"; $jss
- Web 标准要求一览表Russ WeakleyJjgod Jiang14-Aug-2004目录1 Web 标准,不仅仅是“不用表格的站点”2
- 本文实例代码主要实现的是python遍历文件目录的操作,有三种方法,具体代码如下。#coding:utf-8 # 方法1:递归遍历目录 im
- 本文实例讲述了php生成curl命令行的方法。分享给大家供大家参考,具体如下:示例:curl "http://localhost/
- 本文的目的是探讨JS相关技术,并不是以杀毒为主要目的,杀毒只是为讲解一些JS做铺垫的,呵呵,文章有点长,倒杯咖啡或者清茶慢慢看,学习切勿急躁