如何比较Django中的日期 [英] How to compare dates in Django
问题描述
我想比较一个日期到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屋!