2015-11-18 213 views
0

我花了幾個小時試圖找出這一個無濟於事。任何想法爲什麼這個問題發生?Django datetime比較返回None - 爲什麼?

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 =真,{{ product.is_active_by_date }}返回TRUE;但是一旦財產進入日期時間比較線:if datetime.now() < self.activation_date發生了某些錯誤,並返回無。我嘗試打印出datetime.now()和self.activation_date,它們都以相同的格式顯示,例如「2015年11月18日上午10點」並且一切看起來都很好..

這是怎麼回事?任何幫助非常感謝!

+0

在錯誤的情況下,如果您只輸出'{{product}}',您會看到什麼? – Anentropic

回答

1

模板引擎可能吞嚥屬性中的錯誤。嘗試在視圖中訪問product.is_active_by_date以查看返回結果。

如果您啓用了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: 
+0

哦好想法!剛剛嘗試過,它給了我一個錯誤:無法比較偏移天真和偏移意識日期時間 謝謝!這對我來說應該是一個很好的指針 – user2966495

+0

你試過了什麼?在視圖中訪問'product.is_active_by_date',或更改方法以使用'timezone.now()'?你是否啓用了時區支持(在你的設置中檢查「USE_TZ = True」)? – Alasdair

+0

兩者,當我嘗試訪問'product.is_active_by_date'它給了我那個錯誤,然後我'datetime.now()'切換到'timezone.now()',它解決了我的問題!非常感謝你的工作! – user2966495