Django 日期时间比较返回 None - 为什么?
Django datetime comparison returning None - Why?
我花了好几个小时试图解决这个问题,但无济于事。知道为什么会出现这个问题吗??
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 %}
发生的问题是,每当 product.use_activation_date = True 时,{{ product.is_active_by_date }}
returns True;但是,一旦 属性 到达日期时间比较行:if datetime.now() < self.activation_date
就会发生错误,并返回 None。我尝试打印出 datetime.now() 和 self.activation_date,它们都以相同的格式显示,例如"Nov. 18, 2015, 10 a.m." 一切看起来都很好..
这是怎么回事??非常感谢任何帮助!
模板引擎可能正在吞下 属性 中的错误。尝试在视图中访问 product.is_active_by_date
以查看它 returns.
如果启用了 timezone support,则应使用 timezone.now()
而不是 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:
我花了好几个小时试图解决这个问题,但无济于事。知道为什么会出现这个问题吗??
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 %}
发生的问题是,每当 product.use_activation_date = True 时,{{ product.is_active_by_date }}
returns True;但是,一旦 属性 到达日期时间比较行:if datetime.now() < self.activation_date
就会发生错误,并返回 None。我尝试打印出 datetime.now() 和 self.activation_date,它们都以相同的格式显示,例如"Nov. 18, 2015, 10 a.m." 一切看起来都很好..
这是怎么回事??非常感谢任何帮助!
模板引擎可能正在吞下 属性 中的错误。尝试在视图中访问 product.is_active_by_date
以查看它 returns.
如果启用了 timezone support,则应使用 timezone.now()
而不是 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: