在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程序设计入门(1)基本语法简介
Jun 13 Python
Python下singleton模式的实现方法
Jul 16 Python
Python Sleep休眠函数使用简单实例
Feb 02 Python
详解Python的Django框架中的中间件
Jul 24 Python
Python计算斗牛游戏概率算法实例分析
Sep 26 Python
Linux下多个Python版本安装教程
Aug 15 Python
对python的bytes类型数据split分割切片方法
Dec 04 Python
python 实现数字字符串左侧补零的方法
Dec 04 Python
详解Python装饰器
Mar 25 Python
Python容器使用的5个技巧和2个误区总结
Sep 26 Python
python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)
Aug 11 Python
Python基于内置函数type创建新类型
Oct 22 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和.net的区别
2014/09/28 PHP
PHP遍历目录文件的常用方法小结
2017/02/03 PHP
PHP实现在windows下配置sendmail并通过mail()函数发送邮件的方法
2017/06/20 PHP
php实现的pdo公共类定义与用法示例
2017/07/19 PHP
javascript 动态table添加colspan\rowspan 参数的方法
2009/07/25 Javascript
caller和callee的区别介绍及演示结果
2013/03/10 Javascript
Nodejs中自定义事件实例
2014/06/20 NodeJs
JavaScript学习笔记整理_关于表达式和语句
2016/09/19 Javascript
angularJs关于指令的一些冷门属性详解
2016/10/24 Javascript
AngularJS入门教程之Helloworld示例
2016/12/25 Javascript
JS字符串统计操作示例【遍历,截取,输出,计算】
2017/03/27 Javascript
详解vue2.0+vue-video-player实现hls播放全过程
2018/03/02 Javascript
深入浅析javascript函数中with
2018/10/28 Javascript
JavaScript中常用的简洁高级技巧总结
2019/03/10 Javascript
Vue 理解之白话 getter/setter详解
2019/04/16 Javascript
javascript+Canvas实现画板功能
2020/06/23 Javascript
vue使用echarts画组织结构图
2021/02/06 Vue.js
使用Python制作获取网站目录的图形化程序
2015/05/04 Python
Windows下使Python2.x版本的解释器与3.x共存的方法
2015/10/25 Python
python利用Guetzli批量压缩图片
2017/03/23 Python
Python基于hashlib模块的文件MD5一致性加密验证示例
2018/02/10 Python
Python cookbook(数据结构与算法)从字典中提取子集的方法示例
2018/03/22 Python
Python Flask前后端Ajax交互的方法示例
2018/07/31 Python
Django--权限Permissions的例子
2019/08/28 Python
解决python-docx打包之后找不到default.docx的问题
2020/02/13 Python
Python脚本打包成可执行文件过程解析
2020/10/20 Python
财务出纳员岗位职责
2013/11/26 职场文书
土木建筑学生自我评价
2014/01/14 职场文书
班级年度安全计划书
2014/05/01 职场文书
个人房屋买卖协议书(范本)
2014/10/04 职场文书
幼儿园老师新年寄语2015
2014/12/08 职场文书
贷款工作证明模板
2015/06/12 职场文书
停车场管理制度范本
2015/08/05 职场文书
环境保护宣传标语大全!
2019/06/28 职场文书
详解缓存穿透击穿雪崩解决方案
2021/05/28 Redis
解决WINDOWS电脑开机后桌面没有任何图标
2022/04/09 数码科技