Django DateTimeField是朴素的,但USE_TZ=True

2 投票
1 回答
1587 浏览
提问于 2025-04-18 11:44

我在我的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

在settings.py中设置了TIME_ZONE = 'UTC'

安装了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

ends的设置如下:

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 个回答

2

把这一行:

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

改成

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

就解决问题了!

撰写回答