1

I'm trying to make a simple IF function that checks if the date of an item is equal to today or not. Unfortunately I can't get it to work. I basically decides that the statement is false and doesn't show any content, even when it show. I am not getting any error either.

The code I use is following:

{% if item.valid_until.date == now.date %}
  <div id="what_i_want_to_show">
    CONTENT
  </div>
{% endif %}

The content of valid_until is a DateTimeProperty from a Google App Engine app. Normally working with this in Django template doesn't cause any problems. Solutions from similar questions on SO didn't work so far. Am I missing something obvious?

UPDATE 1:

This statement runs in a loop on the result of a database query. Therefore doing the comparison in the view didn't work as far as I could see, since I would have to send the variable with each item.

Vincent
  • 1,137
  • 18
  • 40
  • possible duplicate of [How to compare dates in Django](http://stackoverflow.com/questions/3798812/how-to-compare-dates-in-django) – Lipis Apr 14 '13 at 14:13
  • I've added an update which hopefully explain why this is not a duplicate (as far as I can tell). I checked out the other question but wasn't able to use it as solution. – Vincent Apr 14 '13 at 15:03
  • Please add a listing of your models file, to understand why extra query is done. – singer Apr 14 '13 at 15:06
  • The model represents a coupon with a certain expiration date. Based on this date, I want to present the notification that this is the last day that the coupon is available. To do so, I query the coupons for the page the user is at, and then do this check. Does that explain? – Vincent Apr 14 '13 at 15:14
  • What is `now`? Where is it coming from? – Daniel Roseman Apr 14 '13 at 19:43
  • 'now' should be the django template command for the current date and time. – Vincent Apr 14 '13 at 19:53

1 Answers1

0

There are 2 aproach on this case:

1st: you can add a @property on model

Model:

from datetime import date

@property
def is_past_due(self):
    return timezone.now() > self.valid_until # if valid until default is timezone.now else change it

Template:

{% if item.is_past_due %}
    <!--In the past-->
{% else %}
    {{ item.valid_until.date|date:"Y-m-d" }}
{% endif %}

2nd: declare a today date with format on template

{% now "Y-m-d" as todays_date %}
{% if todays_date  < item.valid_until.date|date:"Y-m-d" %}
  <div id="what_i_want_to_show">
    CONTENT
  </div>
{% endif %}
ohmcodes
  • 69
  • 5