如何比较 Django 模板中的日期 [英] How to compare dates in Django templates
问题描述
我想在 Django 中将日期与当前日期进行比较,最好是在模板中,但也可以在渲染模板之前进行.如果日期已经过去,我想说过去",如果是未来,我想说日期.
I would like to compare a date to the current date in Django, preferably in the template, but it is also possible to do before rendering the template. If the date has already passed, I want to say "In the past" while if it is in the future, I want to give the date.
我希望有人可以做这样的事情:
I was hoping one could do something like this:
{% if listing.date <= now %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}
现在是今天的日期,但这不起作用.我在 Django 文档中找不到任何关于此的信息.谁能给点建议?
With now being today's date, but this does not work. I couldn't find anything about this in the Django docs. Can anyone give some advice?
推荐答案
在视图中比较日期,并将诸如 in_the_past
(boolean) 之类的内容传递给 extra_context.
Compare date in the view, and pass something like in_the_past
(boolean) to the extra_context.
或者更好地将其作为属性添加到模型中.
from datetime import date
@property
def is_past_due(self):
return date.today() > self.date
然后在模板中:
{% if listing.is_past_due %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}
基本上模板不是 IMO 日期比较的地方.
Basically the template is not the place for date comparison IMO.
这篇关于如何比较 Django 模板中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!