在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 相关文章推荐
利用Django框架中select_related和prefetch_related函数对数据库查询优化
Apr 01 Python
python 类详解及简单实例
Mar 24 Python
python select.select模块通信全过程解析
Sep 20 Python
Python smtplib实现发送邮件功能
May 22 Python
Numpy中的mask的使用
Jul 21 Python
python采集微信公众号文章
Dec 20 Python
Python 确定多项式拟合/回归的阶数实例
Dec 29 Python
浅谈python3.x pool.map()方法的实质
Jan 16 Python
Python多进程fork()函数详解
Feb 22 Python
python图片指定区域替换img.paste函数的使用
Apr 09 Python
Python 测试框架unittest和pytest的优劣
Sep 26 Python
python 读取串口数据的示例
Nov 09 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实现过滤掉非汉字字符只保留中文字符
2015/06/04 PHP
php实现微信企业号支付个人的方法详解
2017/07/26 PHP
PHP开发中解决并发问题的几种实现方法分析
2017/11/13 PHP
php生成短网址/短链接原理和用法实例分析
2020/05/29 PHP
jQuery源码分析-04 选择器-Sizzle-工作原理分析
2011/11/14 Javascript
Javascript 修改String 对象 增加去除空格功能(示例代码)
2013/11/30 Javascript
ff下JQuery无法监听input的keyup事件的解决方法
2013/12/12 Javascript
jQuery切换网页皮肤并保存到Cookie示例代码
2014/06/16 Javascript
angularjs学习笔记之三大模块(modal,controller,view)
2015/09/26 Javascript
微信小程序--组件(swiper)详细介绍
2017/06/13 Javascript
详解jQuery中的easyui
2018/09/02 jQuery
基于vue2.0实现仿百度前端分页效果附实现代码
2018/10/30 Javascript
使用koa-log4管理nodeJs日志笔记的使用方法
2018/11/30 NodeJs
Vue-CLI 3.X 部署项目至生产服务器的方法
2019/03/22 Javascript
vue2.0基于vue-cli+element-ui制作树形treeTable
2019/04/30 Javascript
Elementui表格组件+sortablejs实现行拖拽排序的示例代码
2019/08/28 Javascript
VUE.CLI4.0配置多页面入口的实现
2019/11/25 Javascript
axios解决高并发的方法:axios.all()与axios.spread()的操作
2020/11/09 Javascript
写一个Vue loading 插件
2020/11/09 Javascript
[01:18:45]DOTA2-DPC中国联赛 正赛 DLG vs Dragon BO3 第三场2月1日
2021/03/11 DOTA
比较详细Python正则表达式操作指南(re使用)
2008/09/06 Python
python解决字典中的值是列表问题的方法
2013/03/04 Python
python递归查询菜单并转换成json实例
2017/03/27 Python
Python使用pickle模块存储数据报错解决示例代码
2018/01/26 Python
Python编程快速上手——Excel表格创建乘法表案例分析
2020/02/28 Python
如何用python处理excel表格
2020/06/09 Python
Python爬虫爬取ts碎片视频+验证码登录功能
2021/02/22 Python
应用艺术毕业生的自我评价
2013/12/04 职场文书
党员自我批评与反省材料
2014/02/10 职场文书
反腐倡廉演讲稿
2014/05/22 职场文书
医院标语大全
2014/06/23 职场文书
中国梦团日活动总结
2014/07/07 职场文书
做人民满意的公务员活动方案
2014/08/25 职场文书
查摆问题对照检查材料
2014/08/28 职场文书
乡镇党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
什么是Python装饰器?如何定义和使用?
2022/04/11 Python