Django DateTimeField的datetime.now存在问题 [英] Django DateTimeField has problems with datetime.now

查看:57
本文介绍了Django DateTimeField的datetime.now存在问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,存在一个在模型中使用以下定义的通用模式:

In Django exists a common pattern to use the following definition in a model:

some_date = models.DateTimeField(default=datetime.now)

这很麻烦,因为它设置了 some_date的值改为: u'2011-10-18 08:14:30.242000'

This is unfortunately problematic since it sets the value of some_date to something like: u'2011-10-18 08:14:30.242000'.

如果您现在使用表单集让用户提交/编辑其他实例,则该表单将始终被评估为已更改。

If you now use a formset to let the user submit/edit additional instances the form will always evaluate to being changed.

原因是初始日期时间值将为 u'2011-10-18 08:14:30.242000',并且表单小部件中的当前值将为是 u'2011-10-18 08:14:30'。总是不同的。

The reason is that the the initial datetime value will be u'2011-10-18 08:14:30.242000' and the current value from the form widget will be u'2011-10-18 08:14:30'. Which is always different.

不幸的是,我不能写类似 default = currenttime auto_add auto_now_add 的行为不同,并且始终将字段设置为 editable = False

Unfortunately I can't write something like "default=currenttime" and auto_add and auto_now_add have a different behavior and always sets the field to editable=False .

推荐答案

您可以使用模型的save方法,也可以在form.Form

You could use the Model's save method like such or replicate this behaviour in forms.Form

class Something(models.Model):
    pub_date = models.DateTimeField(editable=False)
    change_date = models.DateTimeField(editable=False)

    def save(self, *args, **kwargs):
        if not self.id:
            self.pub_date = datetime.datetime.today()
        self.change_date = datetime.datetime.today()
        super(Something, self).save(*args, **kwargs)

这篇关于Django DateTimeField的datetime.now存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆