Categories
Python Answers

How to compare dates in Python Django templates?

Spread the love

Sometimes, we want to compare dates in Python Django templates.

In this article, we’ll look at how to compare dates in Python Django templates.

How to compare dates in Python Django templates?

To compare dates in Python Django templates, we can add a property into our model to compare the dates.

For instance, we write

from datetime import date

@property
def is_past_due(self):
    return date.today() > self.date

to add the is_past_due computed property into our model that returns if date.today is bigger than `self.date.

Then in our template, we can use it by writing

{% if listing.is_past_due %}
    In the past
{% else %}
    {{ listing.date|date:"d M Y" }}
{% endif %}

Conclusion

To compare dates in Python Django templates, we can add a property into our model to compare the dates.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *