在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自定义函数的创建、调用和函数的参数详解
Mar 11 Python
用Python输出一个杨辉三角的例子
Jun 13 Python
python基础教程之Filter使用方法
Jan 17 Python
python函数的5种参数详解
Feb 24 Python
python实现批量修改文件名代码
Sep 10 Python
Python matplotlib 画图窗口显示到gui或者控制台的实例
May 24 Python
django Serializer序列化使用方法详解
Oct 16 Python
Python用61行代码实现图片像素化的示例代码
Dec 10 Python
Django 迁移、操作数据库的方法
Aug 02 Python
pytorch 常用线性函数详解
Jan 15 Python
Python logging模块写入中文出现乱码
May 21 Python
解决使用Pandas 读取超过65536行的Excel文件问题
Nov 10 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
做一个有下拉功能的留言版
2006/10/09 PHP
一篇不错的PHP基础学习笔记
2007/03/18 PHP
深入解析php模板技术原理【一】
2008/01/10 PHP
php中通过数组进行高效随机抽取指定条记录的算法
2013/09/09 PHP
WordPress中调试缩略图的相关PHP函数使用解析
2016/01/07 PHP
PHP实践教程之过滤、验证、转义与密码详解
2017/07/24 PHP
Laravel框架Auth用户认证操作实例分析
2019/09/29 PHP
面向对象的javascript(笔记)
2009/10/06 Javascript
jQuery获取Select选择的Text和Value(详细汇总)
2013/01/25 Javascript
JavaScript实现的链表数据结构实例
2015/04/02 Javascript
JS对HTML表格进行增删改操作
2016/08/22 Javascript
Node连接mysql数据库方法介绍
2017/02/07 Javascript
three.js中文文档学习之通过模块导入
2017/11/20 Javascript
JS删除数组里的某个元素方法
2018/02/03 Javascript
使用wxapp-img-loader自定义组件实现微信小程序图片预加载功能
2018/10/18 Javascript
JavaScript函数的特性与应用实践深入详解
2018/12/30 Javascript
JavaScript学习笔记之DOM基础操作实例小结
2019/01/09 Javascript
Nodejs让异步变成同步的方法
2019/03/02 NodeJs
js中值引用和地址引用实例分析
2019/06/21 Javascript
javascript读取本地文件和目录方法详解
2020/08/06 Javascript
node.js通过url读取文件
2020/10/16 Javascript
Vue中computed和watch有哪些区别
2020/12/19 Vue.js
python使用正则表达式的search()函数实现指定位置搜索功能
2017/11/10 Python
python中的turtle库函数简单使用教程
2018/07/23 Python
Django REST framwork的权限验证实例
2020/04/02 Python
keras.utils.to_categorical和one hot格式解析
2020/07/02 Python
Python 在函数上添加包装器
2020/07/28 Python
详解Python中Pyyaml模块的使用
2020/10/08 Python
瑜伽国际:Yoga International
2018/04/18 全球购物
Shop Apotheke瑞士:您的健康与美容网上商店
2019/10/09 全球购物
学子宴答谢词
2014/01/25 职场文书
棉花姑娘教学反思
2014/02/15 职场文书
我的祖国演讲稿
2014/05/04 职场文书
建筑工程技术专业求职信
2014/07/16 职场文书
红色旅游心得体会
2014/09/03 职场文书
创业计划之特色精品店
2019/08/12 职场文书