Django DateTimeField很天真但USE_TZ = True

时间:2014-07-01 13:37:23

标签: python django

我在Debian服务器上遇到以下问题。注意:此问题不会发生在本地Mac环境中,相同的代码库。

if self.ends < timezone.now():Exception Type: TypeError at /dealvote/Exception Value: can't compare offset-naive and offset-aware

我做了以下事情:

在settings.py中

USE_TZ = True TIME_ZONE =&#39; UTC&#39;在settings.py中 安装的pytz 安装mysql时区表mysql_tzinfo_to_sql - (如此处所示)

代码:

ends = models.DateTimeField(blank=True)

@property
def isEnded(self):
    if self.ends is not None:

        #Extra check to make sure self.ends is aware
        if timezone.is_naive(self.ends):
            self.ends.replace(tzinfo=timezone.utc)

        #self.ends is not aware here. timezone.now() is aware as checked in django shell
        if self.ends < timezone.now():
            return True
        else:
            return False

结尾设置如下:

def setEnd(self, mins, hrs, dys):
    self.ends = timezone.now()
    isFlashDeal = False

    try:
        minutes = int(mins)
        self.ends += timedelta(minutes=int(mins))
        isFlashDeal = True

    except Exception:
        pass

    try:
        self.ends += timedelta(hours=int(hrs))
        isFlashDeal = True
    except Exception:
        pass

    try:
        self.ends += timedelta(days=int(dys))
        isFlashDeal = True
    except Exception:
        pass

    if isFlashDeal == False:
        self.ends = None

    if timezone.is_naive(self.ends):
        self.ends.replace(tzinfo=timezone.utc)

1 个答案:

答案 0 :(得分:0)

更改此行:

self.ends.replace(tzinfo=timezone.utc)

timezone.make_aware(self.ends, timezone.get_current_timezone())

解决了这个问题!