Django DateTimeField 有 datetime.now 问题
在 Django 中,存在一种在模型中使用以下定义的常见模式:
some_date = models.DateTimeField(default=datetime.now)
不幸的是,这是有问题的,因为它将 some_date
的值设置为:u'2011-10-18 08:14 :30.242000'
。
如果您现在使用表单集让用户提交/编辑其他实例,则表单将始终评估为已更改。
原因是初始日期时间值为 u'2011-10-18 08:14:30.242000'
,表单小部件的当前值将为 u'2011-10- 18 08:14:30'
。这总是不同的。
不幸的是,我无法编写类似 "default=currenttime"
的内容,并且 auto_add
和 auto_now_add
具有不同的行为,并且始终将字段设置为 editable=False
。
In Django exists a common pattern to use the following definition in a model:
some_date = models.DateTimeField(default=datetime.now)
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.
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.
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用模型的 save 方法,或者在 forms.Form 中复制此行为
You could use the Model's save method like such or replicate this behaviour in forms.Form