如何在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
(布尔值)到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屋!