在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的Socket编程过程中实现UDP端口复用的实例分享
Mar 19 Python
Python中字符串格式化str.format的详细介绍
Feb 17 Python
python timestamp和datetime之间转换详解
Dec 11 Python
详解python使用递归、尾递归、循环三种方式实现斐波那契数列
Jan 16 Python
python得到单词模式的示例
Oct 15 Python
python的继承知识点总结
Dec 10 Python
Python3 socket即时通讯脚本实现代码实例(threading多线程)
Jun 01 Python
Python绘制动态水球图过程详解
Jun 03 Python
python正则表达式re.match()匹配多个字符方法的实现
Jan 27 Python
浅谈Python numpy创建空数组的问题
May 25 Python
Python selenium绕过webdriver监测执行javascript
Apr 12 Python
Github 使用python对copilot做些简单使用测试
Apr 14 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实现多服务器session共享之NFS共享的方法
2007/03/16 PHP
php gd2 上传图片/文字水印/图片水印/等比例缩略图/实现代码
2010/05/15 PHP
php实现字符串首字母转换成大写的方法
2015/03/17 PHP
Yii2使用swiftmailer发送邮件的方法
2016/05/03 PHP
无需数据库在线投票调查php代码
2016/07/20 PHP
PHP实现的CURL非阻塞调用类
2018/07/26 PHP
JavaScript 高级语法介绍
2009/06/15 Javascript
使用原生JS实现弹出层特效
2014/12/22 Javascript
JavaScript中的函数模式详解
2015/02/11 Javascript
jquery简单实现带渐显效果的选项卡菜单代码
2015/09/01 Javascript
AngularJS入门教程一:路由用法初探
2017/05/27 Javascript
vue将毫秒数转化为正常日期格式的实例
2018/09/16 Javascript
新手必须知的Node.js 4个JavaScript基本概念
2018/09/16 Javascript
vue-cli 3.0 自定义vue.config.js文件,多页构建的方法
2018/09/19 Javascript
用WebStorm进行Angularjs 2开发(环境篇:Windows 10,Angular-cli方式)
2018/12/05 Javascript
JavaScript设计模式之代理模式实例分析
2019/01/16 Javascript
解决layui表格内文本超出隐藏的问题
2019/09/12 Javascript
环形加载进度条封装(Vue插件版和原生js版)
2019/12/04 Javascript
js中火星坐标、百度坐标、WGS84坐标转换实现方法示例
2020/03/02 Javascript
寻找网站后台地址的python脚本
2014/09/01 Python
python自动化测试之从命令行运行测试用例with verbosity
2014/09/28 Python
Python中splitlines()方法的使用简介
2015/05/20 Python
基于循环神经网络(RNN)实现影评情感分类
2018/03/26 Python
Python网络爬虫之爬取微博热搜
2019/04/18 Python
详解使用django-mama-cas快速搭建CAS服务的实现
2019/10/30 Python
python实现快速文件格式批量转换的方法
2020/10/16 Python
美国南部最大的家族百货公司:Belk
2017/01/30 全球购物
香港唯港荟酒店预订:Hotel ICON
2018/03/27 全球购物
美国一家著名的手表在线折扣网站:Discount Watch Store
2020/02/24 全球购物
介绍一下Ruby中的对象,属性和方法
2012/07/11 面试题
2014年学校工作总结
2014/11/20 职场文书
借条如何写
2015/05/26 职场文书
少年派的奇幻漂流观后感
2015/06/08 职场文书
团支部组织委员竞选稿
2015/11/21 职场文书
让人感觉高大上的讲话稿怎么写?
2019/07/08 职场文书
利用 JavaScript 构建命令行应用
2021/11/17 Javascript