-1

I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me.

My code:

modelys.py

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)

views.py

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

home.html

{% if customer.last_updated.is_past_due %}
<td class="table-danger">{{ customer.last_updated }}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated }}</td>
{% endif %}

I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes.

Thanks in advance.

PS: edited the typo in def timdedelta to timedelta.

kingbrain
  • 116
  • 12

2 Answers2

0

you can use days property of datetime to get the exact gap between days.

(datetime.today()- self.last_updated).days > 1 where self.last_updated is field name of "Customer" Model

Ankush
  • 1,783
  • 2
  • 10
  • 15
  • Thank you for your answer. That is basically the way if you want to get the number which you can compare directly, whereas the without '.days' you have to use timedelta. But unfortunately this does not solve my problem. :-( – kingbrain Dec 05 '17 at 09:33
  • you want your function to return "True" or "False". Here, the condition > 1 will do this for you. Do let me know if I'm understanding your problem incorrectly. Thanks. – Ankush Dec 05 '17 at 09:39
  • My goal is that I have in the template the if clause. I have two conditions. 1.) When difference of today-last_updated date is larger than 1 then I want that the first condition is done 2.) otherwise. But as far as I see 'is_past_due' is not called properly. Even if I write return True it does not change. I still see I am a newbie and don't knows some basics. – kingbrain Dec 05 '17 at 09:55
  • @kingbrain, make property method be the part of your model class and inside your template use that directly. ie {% if customer.is_past_due %} – Ankush Dec 05 '17 at 10:38
0

Here the final code as sumup of the posts:

models.py

from datetime import datetime

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)
#...some more code...
    @property
    def is_past_due(self):
        return (datetime.now(timezone.utc) - self.last_updated).days>1

home.html

{% if customer.is_past_due %}
<td class="align-middle table-danger">{{ customer.last_updated.date}}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated}}</td>
{% endif %}
kingbrain
  • 116
  • 12