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 %}
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?
解决方案
Compare date in the view, and pass something like in_the_past (boolean) to the extra_context.
Or better add it to the model as a property.
from datetime import date
@property
def is_past_due(self):
return date.today() > self.date
Then in the view:
{% if listing.is_past_due %}
In the past
{% else %}
{{ listing.date|date:"d M Y" }}
{% endif %}
Basically the template is not the place for date comparison IMO.