How to compare dates in Django templates

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 template:

{% 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.


As of Django 1.8 the following slightly distasteful construct does the job:

{% now "Y-m-d" as todays_date %}
{% if todays_date < someday|date:"Y-m-d" %}
   <h1>It's not too late!</h1>
{% endif %}

Hackish, but it avoids the need for a custom tag or context processor.


I added date_now to my list of context processors.

So in the template there's a variable called "date_now" which is just datetime.datetime.now()

Make a context processor called date_now in the file context_processors.py

import datetime

def date_now(request):
    return {'date_now':datetime.datetime.now()}

And in settings.py, modify CONTEXT_PROCESSORS to include it, in my case it's

app_name.context_processors.date_now