user2966495
user2966495

Reputation: 157

Django datetime comparison returning None - Why?

I've spent hours trying to figure this one out to no avail.. Any idea why this problem is happening??

models.py

from datetime import date, datetime

class Product(models.Model):
    use_activation_date = models.BooleanField(default=False)
    activation_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True

    @property
    def is_active_by_date(self):
        if self.use_activation_date:
            if datetime.now() < self.activation_date:
                return False #is not active because current date is before activate date
            else:
                return True #is active because date is = or past activation_date
        else:
            return True #is active because not using activation date

template.html

                {% if not product.is_active_by_date %}
              <!-- here is the problem, it is not returning True nor False! -->
                  {{ product.is_active_by_date }} <!-- getting blank result here -->
                  Product is not active 
                {% else %}
                  {{ product.is_active_by_date }}
                  Product is active
                 {% endif %}

The problem happening is, whenever product.use_activation_date = True , {{ product.is_active_by_date }} returns True; however once the property gets to the datetime comparison line: if datetime.now() < self.activation_date something wrong happens and None is returned. I tried printing out datetime.now() and self.activation_date and they both display in an equal format e.g. "Nov. 18, 2015, 10 a.m." and everything looks fine..

What is going on ?? Any help is tremendously appreciated!

Upvotes: 0

Views: 310

Answers (1)

Alasdair
Alasdair

Reputation: 309109

It's possible that the template engine is swallowing an error in the property. Try accessing product.is_active_by_date in the view to see what it returns.

If you have timezone support enabled, you should use timezone.now() instead of datetime.now().

from django.utils import timezone

class Product(models.Model):
    @property
    def is_active_by_date(self):
        if self.use_activation_date:
        if timezone.now() < self.activation_date:

Upvotes: 1

Related Questions