在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专用方法与迭代机制实例分析
Sep 15 Python
Python压缩和解压缩zip文件
Feb 14 Python
Python中列表和元组的相关语句和方法讲解
Aug 20 Python
Python的Twisted框架中使用Deferred对象来管理回调函数
May 25 Python
Python 出现错误TypeError: ‘NoneType’ object is not iterable解决办法
Jan 12 Python
python实现装饰器、描述符
Feb 28 Python
Python 删除连续出现的指定字符的实例
Jun 29 Python
Python 字符串与数字输出方法
Jul 16 Python
python实时获取外部程序输出结果的方法
Jan 12 Python
python基于socket实现的UDP及TCP通讯功能示例
Nov 01 Python
Python多重继承之菱形继承的实例详解
Feb 12 Python
如何把python项目部署到linux服务器
Aug 26 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
浅谈电磁辐射对健康的影响
2021/03/01 无线电
php操作sqlserver关于时间日期读取的小小见解
2009/11/29 PHP
PHP利用Socket获取网站的SSL证书与公钥
2017/06/18 PHP
php检测mysql表是否存在的方法小结
2017/07/20 PHP
基于PHP实现的多元线性回归模拟曲线算法
2018/01/30 PHP
JavaScript prototype属性使用说明
2010/05/13 Javascript
JSON.parse 解析字符串出错的解决方法
2010/07/08 Javascript
Javascript insertAfter() 实现函数代码
2011/10/12 Javascript
jQuery中delegate和on的用法与区别详细解析
2014/01/26 Javascript
jQuery实现购物车数字加减效果
2015/03/14 Javascript
jquery插件star-rating.js实现星级评分特效
2015/04/15 Javascript
JavaScript驾驭网页-DOM
2016/03/24 Javascript
JS判断指定dom元素是否在屏幕内的方法实例
2017/01/23 Javascript
jquery 校验中国身份证号码实例详解
2017/04/11 jQuery
浅谈JavaScript中的属性:如何遍历属性
2017/09/14 Javascript
仿淘宝JSsearch搜索下拉深度用法
2018/01/15 Javascript
详解vantUI框架在vue项目中的应用踩坑
2018/12/06 Javascript
如何解决webpack-dev-server代理常切换问题
2019/01/09 Javascript
详解vue 路由跳转四种方式 (带参数)
2019/04/28 Javascript
element-ui表格合并span-method的实现方法
2019/05/21 Javascript
ES6中Set和Map用法实例详解
2020/03/02 Javascript
[03:54]DOTA2英雄梦之声_第06期_昆卡
2014/06/23 DOTA
python3中zip()函数使用详解
2018/06/29 Python
Python提取转移文件夹内所有.jpg文件并查看每一帧的方法
2019/06/27 Python
Flask框架学习笔记之消息提示与异常处理操作详解
2019/08/15 Python
python 扩展print打印文件路径和当前时间信息的实例代码
2019/10/11 Python
在Python中画图(基于Jupyter notebook的魔法函数)
2019/10/28 Python
python基于celery实现异步任务周期任务定时任务
2019/12/30 Python
python numpy实现多次循环读取文件 等间隔过滤数据示例
2020/03/14 Python
css3实现画半圆弧线的示例代码
2017/11/06 HTML / CSS
高三历史教学反思
2014/01/09 职场文书
机械加工与数控专业自荐书
2014/06/04 职场文书
感谢信的格式
2015/01/21 职场文书
投标邀请书范本
2015/02/02 职场文书
高一数学教学反思
2016/02/18 职场文书
Oracle配置dblink访问PostgreSQL的操作方法
2022/03/21 PostgreSQL