在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 3.x 新特性及10大变化
Jun 12 Python
Python写的一个定时重跑获取数据库数据
Dec 28 Python
Python找出最小的K个数实例代码
Jan 04 Python
Python爬虫PyQuery库基本用法入门教程
Aug 04 Python
Python字符串对象实现原理详解
Jul 01 Python
使用Python和Scribus创建一个RGB立方体的方法
Jul 17 Python
pycharm创建scrapy项目教程及遇到的坑解析
Aug 15 Python
在Python3 numpy中mean和average的区别详解
Aug 24 Python
Python通过Pillow实现图片对比
Apr 29 Python
Python调用百度OCR实现图片文字识别的示例代码
Jul 17 Python
python集合的新增元素方法整理
Dec 07 Python
Sentry的安装、配置、使用教程(Sentry日志手机系统)
Jul 23 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+mysql一个名片库程序
2006/10/09 PHP
js下函数般调用正则的方法附代码
2008/06/22 PHP
php采集文章中的图片获取替换到本地(实现代码)
2013/07/08 PHP
PHP加密扩展库Mcrypt安装和实例
2013/11/10 PHP
JavaScript 动态将数字金额转化为中文大写金额
2009/05/14 Javascript
Javascript拓展String方法小结
2013/07/08 Javascript
浮动的div自适应居中显示的js代码
2013/12/23 Javascript
JS在浏览器中解析Base64编码图像
2017/02/09 Javascript
NodeJS 实现手机短信验证模块阿里大于功能
2017/06/19 NodeJs
vue使用axios时关于this的指向问题详解
2017/12/22 Javascript
AngularJS基于MVC的复杂操作实例讲解
2017/12/31 Javascript
VueJs监听window.resize方法示例
2018/01/17 Javascript
JS函数内部属性之arguments和this实例解析
2018/10/07 Javascript
Vue CLI2升级至Vue CLI3的方法步骤
2019/05/20 Javascript
百度小程序自定义通用toast组件
2019/07/17 Javascript
vue实现用户长时间不操作自动退出登录功能的实现代码
2020/07/23 Javascript
跟老齐学Python之画圈还不简单吗?
2014/09/20 Python
使用Python编写简单的画图板程序的示例教程
2015/12/08 Python
Python编程生成随机用户名及密码的方法示例
2017/05/05 Python
Python利用字典将两个通讯录文本合并为一个文本实例
2018/01/16 Python
python http基本验证方法
2018/12/26 Python
Python英文文本分词(无空格)模块wordninja的使用实例
2019/02/20 Python
Django+Xadmin构建项目的方法步骤
2019/03/06 Python
Python制作微信好友背景墙教程(附完整代码)
2019/07/17 Python
Python利用matplotlib绘制约数个数统计图示例
2019/11/26 Python
Python安装tar.gz格式文件方法详解
2020/01/19 Python
利用python实现逐步回归
2020/02/24 Python
前后端结合实现amazeUI分页效果
2020/08/21 HTML / CSS
伊利莎白雅顿官网:Elizabeth Arden
2016/10/10 全球购物
大学同学十年聚会感言
2014/02/21 职场文书
党支部2014年度工作总结
2014/12/04 职场文书
世界卫生日宣传活动总结
2015/02/09 职场文书
省级三好学生主要事迹材料
2015/11/03 职场文书
党员公开承诺书(2016最新版)
2016/03/24 职场文书
python正则表达式re.search()的基本使用教程
2021/05/21 Python
OpenCV-Python模板匹配人眼的实例
2021/06/08 Python