在Django中自定义filter并在template中的使用详解


Posted in Python onMay 19, 2020

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中自定义filter并在template中的使用详解

补充知识: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', {}),
    ))

以上这篇在Django中自定义filter并在template中的使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解Python中 __get__和__getattr__和__getattribute__的区别
Jun 16 Python
python机器学习库常用汇总
Nov 15 Python
python 读取目录下csv文件并绘制曲线v111的方法
Jul 06 Python
Python中常用的内置方法
Jan 28 Python
Django中celery执行任务结果的保存方法
Jul 12 Python
pandas条件组合筛选和按范围筛选的示例代码
Aug 26 Python
在Mac中PyCharm配置python Anaconda环境过程图解
Mar 11 Python
详解Python3中的 input() 函数
Mar 18 Python
浅谈django 模型类使用save()方法的好处与注意事项
Mar 28 Python
Python如何实现的二分查找算法
May 27 Python
python实现学生成绩测评系统
Jun 22 Python
利用python制作拼图小游戏的全过程
Dec 04 Python
Django Model中字段(field)的各种选项说明
May 19 #Python
Django模板获取field的verbose_name实例
May 19 #Python
Django多层嵌套ManyToMany字段ORM操作详解
May 19 #Python
django ORM之values和annotate使用详解
May 19 #Python
基于python实现地址和经纬度转换
May 19 #Python
Python Django form 组件动态从数据库取choices数据实例
May 19 #Python
Django自关联实现多级联动查询实例
May 19 #Python
You might like
使用openssl实现rsa非对称加密算法示例
2014/01/24 PHP
在表单提交前进行验证的几种方式整理
2013/07/31 Javascript
用js+iframe形成页面的一种遮罩效果的具体实现
2013/12/31 Javascript
js检测输入内容全为空格的方法
2014/05/03 Javascript
JS实现网页标题栏显示当前时间和日期的完整代码
2015/11/02 Javascript
Node.js重新刷新session过期时间的方法
2016/02/04 Javascript
JavaScript基于原型链的继承
2016/06/22 Javascript
React Native自定义控件底部抽屉菜单的示例
2018/02/08 Javascript
详解JavaScript的BUG和错误
2018/05/07 Javascript
关于在vue 中使用百度ueEditor编辑器的方法实例代码
2018/09/14 Javascript
vue实现动态显示与隐藏底部导航的方法分析
2019/02/11 Javascript
js实现AI五子棋人机大战
2020/05/28 Javascript
Nodejs文件上传、监听上传进度的代码
2020/03/27 NodeJs
js实现鼠标滑动到某个div禁止滚动
2020/09/17 Javascript
[01:10]DOTA2次级职业联赛 - EP战队宣传片
2014/12/01 DOTA
python使用Queue在多个子进程间交换数据的方法
2015/04/18 Python
Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例
2017/08/31 Python
python散点图实例之随机漫步
2018/08/27 Python
在Python中获取两数相除的商和余数方法
2018/11/10 Python
Python操作mongodb数据库的方法详解
2018/12/08 Python
Python操作Mongodb数据库的方法小结
2019/09/10 Python
浅谈图像处理中掩膜(mask)的意义
2020/02/19 Python
浅谈keras中的后端backend及其相关函数(K.prod,K.cast)
2020/06/29 Python
python boto和boto3操作bucket的示例
2020/10/30 Python
python利用opencv保存、播放视频
2020/11/02 Python
前端面试必备之html5的新特性
2017/09/05 HTML / CSS
html5+css3实现一款注册表单实例
2013/04/17 HTML / CSS
微信浏览器取消缓存的方法
2015/03/28 HTML / CSS
Willer台湾:日本高速巴士/夜行巴士预约
2017/07/09 全球购物
汉森冲浪板:Hansen Surfboards
2018/05/19 全球购物
Mio Skincare英国官网:身体紧致及孕期身体护理
2018/08/19 全球购物
英国Lookfantastic中文网站:护肤品美妆美发购物(英国直邮)
2020/04/27 全球购物
研究生求职推荐信范文
2013/11/30 职场文书
大学生个人自荐信样本
2014/03/02 职场文书
临床医学专业求职信
2014/08/08 职场文书
护理专业自我评价
2015/03/11 职场文书