在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的Django框架环境并建立和运行第一个App的教程
Jul 02 Python
基于Django的ModelForm组件(详解)
Dec 07 Python
python 获取list特定元素下标的实例讲解
Apr 09 Python
使用python存储网页上的图片实例
May 22 Python
Python日期时间模块datetime详解与Python 日期时间的比较,计算实例代码
Sep 14 Python
kafka-python批量发送数据的实例
Dec 27 Python
Python 硬币兑换问题
Jul 29 Python
python自动化UI工具发送QQ消息的实例
Aug 27 Python
python数据处理之如何选取csv文件中某几行的数据
Sep 02 Python
opencv3/C++图像像素操作详解
Dec 10 Python
使用Python-OpenCV消除图像中孤立的小区域操作
Jul 05 Python
Python3 搭建Qt5 环境的方法示例
Jul 16 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 计划任务 检测用户连接状态
2012/03/29 PHP
在浏览器中获取当前执行的脚本文件名的代码
2011/07/19 Javascript
利用div+jquery自定义滚动条样式的2种方法
2013/07/18 Javascript
地址栏传递中文参数乱码在js里用escape转码
2013/08/28 Javascript
node.js中的console.log方法使用说明
2014/12/09 Javascript
js实现本地图片文件拖拽效果
2017/07/18 Javascript
详解如何实现Element树形控件Tree在懒加载模式下的动态更新
2019/04/25 Javascript
Vue数据驱动表单渲染,轻松搞定form表单
2019/07/19 Javascript
小程序调用微信支付的方法
2019/09/26 Javascript
WEB前端性能优化的7大手段详解
2020/02/04 Javascript
vue中改变滚动条样式的方法
2020/03/03 Javascript
JavaScript中CreateTextFile函数
2020/08/30 Javascript
解决vue scoped html样式无效的问题
2020/10/24 Javascript
[02:30]辉夜杯主赛事第二日胜者组半决赛 CDEC.Y赛后采访
2015/12/26 DOTA
python list语法学习(带例子)
2013/11/01 Python
总结用Pdb库调试Python的方式及常用的命令
2016/08/18 Python
浅谈python中列表、字符串、字典的常用操作
2017/09/19 Python
python使用openpyxl库修改excel表格数据方法
2018/05/03 Python
Python实现的绘制三维双螺旋线图形功能示例
2018/06/23 Python
django如何连接已存在数据的数据库
2018/08/14 Python
Python Multiprocessing多进程 使用tqdm显示进度条的实现
2019/08/13 Python
python GUI库图形界面开发之PyQt5信号与槽事件处理机制详细介绍与实例解析
2020/03/08 Python
Python3标准库glob文件名模式匹配的问题
2020/03/13 Python
怎么快速自学python
2020/06/22 Python
详解如何修改python中字典的键和值
2020/09/29 Python
基于IE10/HTML5 开发
2013/04/22 HTML / CSS
英国骑行、跑步、游泳、铁人三项运动装备专卖店:Wiggle
2016/08/23 全球购物
德国价格合理的品牌商品购物网站:averdo
2019/03/21 全球购物
广播电视新闻学专业应届生求职信
2013/10/08 职场文书
农民工工资承诺书范文
2014/03/31 职场文书
美容院经理岗位职责
2014/04/03 职场文书
公司领导班子四风对照检查材料
2014/09/27 职场文书
2015年世界水日活动总结
2015/02/09 职场文书
2016领导干部廉洁自律心得体会
2016/01/13 职场文书
浅谈:电影《孔子》观后感(范文)
2019/10/14 职场文书
MySQL数据库之存储过程 procedure
2022/06/16 MySQL