Django自定义过滤器
1、在App建立文件夹 templatetags
2、在templatetags里 建立my_filter.py文件
例子:
# 需求:发表微博 或者 空间动态的时候 一般不会直接显示发布的精确时间
#而是 刚刚 *分钟之前 *小时之前 *天前 超过这些时间 显示 年月日 时分秒
from datetime import datetime
from django import template
register = template.Library()
def time_since(value):
'''
刚刚 1分钟以内
大于1分钟 小于1小时 多少分钟之前
大于1小时 小于 24小时 几个小时之前
大于24小时 小于30天 几天前
'''
now = datetime.now()
timestamp = (now-value).total_seconds()
if timestamp < 60:
return '刚刚来过'
elif timestamp >= 60 and timestamp<3600:
minutes = int(timestamp/60)
return '%s 分钟前来过'%minutes
elif timestamp >=3600 and timestamp < 60*60*24:
hour = int(timestamp/3600)
return '%s小时之前' % hour
elif timestamp >= 60 * 60 * 24 and timestamp <= 60 * 60 * 24 * 30:
days = int(timestamp / 60 / 60 / 24)
return '%s天之前' % days
else:
return value.strftime("%Y-%m-%d %H:%M")
register.filter('times',time_since) # 定义过滤器名
3、setting.py中
# 此处不设置,会报错 is not a registered tag library. Must be one of...
templates中中括号后
添加
'libraries':{
'my_customer_tags': 'APP名字.templatetags.过滤器文件名',
}
4、网页模板中引入
{% load 过滤器文件名 %}
{{ value| 过滤器名 }}