belek
belek

Reputation: 957

Compare datetime year to current year in django template

I need to compare a year from object's DateTime field value with current year in my template. And if years are not same, show the object's year. This is how I am doing this:

{% now "Y" as current_year %}
    <ul>
        {% for news in news %}
            {% if news.date.year != current_year %}
                <b>{{ news.date.year }}</b>
                <li>{{ news }}</li>
            {% else %}
                <li>{{ news }}</li>
            {% endif %}
        {% endfor %}
    </ul>

And it is always true and displays me the year. But if I use 2015 instead of current_year it works fine.

Basically I need to have this:

Upvotes: 1

Views: 2610

Answers (1)

xyres
xyres

Reputation: 21744

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 %}

Upvotes: 1

Related Questions