我目前正在使用Django-Messages,可以看到收到消息的确切日期和时间。我正在尝试构建一个模板过滤器,它接受接收的日期/时间,然后计算它是否是今天,昨天,上周,等等。
Inbox.html
Inbox | Received Today
{% for message in messages %}
{% if message.date|hours_ago:24 %}
Today
Sent by: {{ message.sender }}
{{ message.body }}
{% elif message.date|hours_ago:48 %}
Yesterday
Sent by: {{ message.sender }}
{{ message.body }
{% endif %}
{% endfor %}模板过滤器
@register.filter
def hours_ago(time, hours):
return time + timedelta(hours=hours) < timezone.now()这目前不起作用。例如,无论message.date值如何,{% if message.date|hours_ago:3 %}都将显示所有电子邮件。
知道message.date本身(没有模板筛选器)以“12.17,2014,6:21 a.m”的格式显示可能会有所帮助,我不知道这是否与模板筛选器不工作有关。
发布于 2014-12-18 16:30:24
尝试从Python shell调用hours_ago()函数,您会发现第一个问题:
>>> TypeError: can't compare datetime.datetime to function哦,那应该是:
return time + timedelta(hours=hours) < timezone.now()注意下面的括号..。
现在,上面的表达式仍然不能实现您希望的结果:
>>> timezone.now()
datetime.datetime(2014, 12, 18, 9, 26, 57, 920331)
>>> t = datetime.datetime(2014, 11, 5)
>>> hours_ago(t, 24)
True
>>> hours_ago(t, 48)
True重点是:实际上,您对传入的datetime的函数检查是“比hours旧的多”。这意味着对于30天前的datetime,对于任何小于(大约) 720 (=> 30 * 24)的hours值,都将返回True。
显然,你需要更多地考虑你希望这个过滤器到底能做什么……首先编写单元测试可能也会有所帮助。
https://stackoverflow.com/questions/27541651
复制相似问题