在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 相关文章推荐
在Apache服务器上同时运行多个Django程序的方法
Jul 22 Python
Python基础教程之利用期物处理并发
Mar 29 Python
对python多线程中Lock()与RLock()锁详解
Jan 11 Python
python字符串查找函数的用法详解
Jul 08 Python
对YOLOv3模型调用时候的python接口详解
Aug 26 Python
Pytorch GPU显存充足却显示out of memory的解决方式
Jan 13 Python
Python爬虫小例子——爬取51job发布的工作职位
Jul 10 Python
python实现数字炸弹游戏
Jul 17 Python
python自动化测试三部曲之unittest框架的实现
Oct 07 Python
python实现学生通讯录管理系统
Feb 25 Python
解决numpy和torch数据类型转化的问题
May 23 Python
python用tkinter开发的扫雷游戏
Jun 01 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
php设计模式 Strategy(策略模式)
2011/06/26 PHP
无刷新动态加载数据 滚动条加载适合评论等页面
2013/10/16 PHP
编写PHP脚本清除WordPress头部冗余代码的方法讲解
2016/03/01 PHP
php基于环形链表解决约瑟夫环问题示例
2017/11/07 PHP
阿里云Win2016安装Apache和PHP环境图文教程
2018/03/11 PHP
JS正则中的RegExp对象对象
2012/11/07 Javascript
实现只能输入数字的input不用replace方法
2013/09/12 Javascript
js clearInterval()方法的定义和用法
2015/11/11 Javascript
鼠标悬停小图标显示大图标
2016/01/22 Javascript
jQuery获取多种input值的简单实现方法
2016/06/20 Javascript
又一款js时钟!transform实现时钟效果
2016/08/15 Javascript
微信js-sdk地理位置接口用法示例
2016/10/12 Javascript
Javascript使用SWFUpload进行多文件上传
2016/11/16 Javascript
在页面中引入js的两种方法(推荐)
2017/08/29 Javascript
js实现控制文件拖拽并获取拖拽内容功能
2018/02/17 Javascript
JS实现排行榜文字向上滚动轮播效果
2019/11/26 Javascript
解决ant Design Search无法输入内容的问题
2020/10/29 Javascript
[48:35]2018DOTA2亚洲邀请赛 4.1 小组赛 A组加赛 TNC vs Optic
2018/04/03 DOTA
python写的一个squid访问日志分析的小程序
2014/09/17 Python
python实现根据用户输入从电影网站获取影片信息的方法
2015/04/07 Python
在Python中使用swapCase()方法转换大小写的教程
2015/05/20 Python
Python连接数据库学习之DB-API详解
2017/02/07 Python
python实现将range()函数生成的数字存储在一个列表中
2020/04/02 Python
html5+css3进度条倒计时动画特效代码【推荐】
2016/03/08 HTML / CSS
美国温暖商店:The Warming Store
2018/12/15 全球购物
敏捷开发的主要原则都有哪些
2015/04/26 面试题
视光学专业毕业生推荐信
2013/10/28 职场文书
我的网上商城创业计划书
2013/12/26 职场文书
结婚邀请函范文
2014/01/14 职场文书
会议室标语
2014/06/21 职场文书
2014年企业团支部工作总结
2014/12/10 职场文书
2019大学生预备党员转正思想汇报
2019/06/21 职场文书
如何将JavaScript将数组转为树形结构
2021/06/02 Javascript
JavaCV实现照片马赛克效果
2022/01/22 Java/Android
Python实现简单得递归下降Parser
2022/05/02 Python
create-react-app开发常用配置教程
2022/06/25 Javascript