在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
0
投稿
猜你喜欢
- 说到Javascript的类继承,就必然离不开原型链,但只通过原型链实现的继承有着不少缺陷。无参数类继承的问题先看一段示例代码,实现B继承于
- 哎~工作忙死了!!!!!!今天在百度老年看到一个手写输入法,颇感新鲜。so把其框下!请不要用在商业用途,学习之用,版权百度所有。看代码!注:
- 首先编写py程序:printtest.pydef test(): print('print test')将以上.
- 1. 迭代根据记录的前面的元素的位置信息 去访问后续的元素的过程 -遍历 迭代2. 可迭代对象 iterable如何判断可迭代对象的3种方式
- 前言:图像处理是常用的技术,python 拥有丰富的第三方扩展库,Pillow 是 Python3 最常用的图像处理库,目前最高版本5.2.
- Mysql Explain 详解一.语法explain < table_name >例如: explain select * f
- 对象:是抽象的概念 如列表 元组 字典 集合 皆为对象序列化:一种方法。目的:把对象存储在磁盘上(即,将对象转换为字节数据/字符数据)。这一
- 1. 数据筛选 a b c0 0 2 41 6 8 102 12 14 163 18 20 224 24 26 285 30 32 346
- 主要作用与拷贝文件用的。1.shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。import shu
- urllib的基本用法urllib库的基本组成利用最简单的urlopen方法爬取网页html利用Request方法构建headers模拟浏览
- 一个不错的二级联动下拉菜单源码,您一定会用得到的。运行代码:<html><head><title>Lis
- <table border="1" cellpadding="0&quo
- pip 是 Python 包管理工具,该工具提供了对Python 包的查找、下载、安装、卸载的功能。pip检测更新命令:pip list –
- 二值图像的凸壳指的是包围输入二值图像白色区域的最小的凸多边形的像素集合。skimage中的函数from skimage.morphology
- 漂亮的代码是漂亮网站的基础,优秀的 CSS 只存在与同样优秀的 HTML 之上,干净的,语义的 HTML 代码让一个网站更健壮。本文讲述了1
- 在Windows平台下,如果想运行爬虫的话,就需要在cmd中输入:scrapy crawl spider_name这时,爬虫就能启动,并在控
- Python装饰器用法Python的装饰器是个好东西,它能干很多事情。但对于新手,它看起来似乎没那么简单。但事实上,装饰器本身也只是个函数。
- #!/usr/bin/python#-*-coding:utf-8-*-# JCrawler# Author: Jam <810441
- 环境准备 python3.52 pycharm5.05 Pillow 自制的验证码工具包/utils/check_code 验证码的作用防恶
- keras中卷积层Conv2D的学习关于卷积的具体操作不细讲,本文只是自己太懒了不想记手写笔记。由于自己接触到的都是图像处理相关的工作,因此