关于django:如何修复RuntimeWarning:DateTimeField收到一个天真的>

how to fix RuntimeWarning: DateTimeField received a naive > datetime while time zone support is active?

完全回溯

C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\fields__init__.py:1451:
RuntimeWarning: DateTimeField UserProfile.key_expires received a naive
datetime (2017-07-04 14:18:43) while time zone support is active.
RuntimeWarning)

这是我的用户配置文件模型

1
2
3
4
5
class UserProfile(models.Model):
    user                                        = models.OneToOneField(User, on_delete=models.CASCADE)
    slug                                        = models.SlugField(unique=False, default=None, blank=True)
    activation_key                              = models.CharField(max_length=90, default=None, blank=True)
    key_expires                                 = models.DateTimeField(default=None)

这是视图

1
2
3
4
5
6
profile = UserProfile.objects.create(
                user=user,
                slug=username,
                key_expires=datetime.datetime.strftime(timezone.now() + datetime.timedelta(days=2),"%Y-%m-%d %H:%M:%S"),
                activation_key=get_secret_key
                )


当时区支持处于活动状态时,您确实应该使用timezone.now()。但不需要用字符串初始化datetimefield,django将直接处理datetime对象。

因此,要保持TZ感知日期时间,您应该编写:

1
2
3
4
5
6
7
8
from django.utils import timezone

profile = UserProfile.objects.create(
    user=user,
    slug=username,
    key_expires=timezone.now() + datetime.timedelta(days=2),
    activation_key=get_secret_key
)