[Fixed]-Compare datetime year to current year in django template

1👍

I don’t think it can be done the way you’re trying to do it. But you can certainly write a method for your model which checks if the year is same.

from django.utils import timezone

class MyModel(...):
    # fields ...
    date = models.DateField(...)

    def was_published_this_year(self):
        return timezone.now().year == self.date.year

Now, in your templates do like this:

{% if not news.was_published_this_year %}
    Do something.
{% endif %}
👤xyres

Leave a comment