Django DateTimeField 在未编辑时变为 null
基本上我的 ModelForm 上有这段代码:
def save(self):
if not self.instance.pk:
self.instance.author = self.author
self.instance.date_sorted = datetime.now()
return super(PostForm, self).save(commit = True)
我的目的是仅在添加记录时保存 date_sorted ,并在编辑时忽略它。我的 date_sorted 字段定义为:
date_sorted = models.DateTimeField(blank = True, null = True)
我定义了 Blank=True 和 null=True ,因为在某些时候我希望某些 date_sorted 为空(故意)。
添加时,date_sorted 将存储当前日期和时间,但在编辑(更新其他字段)时,date_sorted 更改为 NULL。试图在网上找到类似的问题,但没有运气:(。任何帮助表示赞赏。
Basically I have this code on my ModelForm:
def save(self):
if not self.instance.pk:
self.instance.author = self.author
self.instance.date_sorted = datetime.now()
return super(PostForm, self).save(commit = True)
My purpose it to only save date_sorted upon adding a record, and ignore it when editing. My date_sorted field is defined as:
date_sorted = models.DateTimeField(blank = True, null = True)
I defined blank=True and null=True on that because at some point I want some of the date_sorted to be null (on purpose).
When adding, the date_sorted will store the current date and time, but when editing (updating other fields), the date_sorted is changed to NULL. Tried to find similar issues on the net but no luck :(. Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个,它会隐藏表单中的日期时间字段,并在您发布消息时自动设置日期:
另外,您可以使用 save_model 方法:
我将其用于管理面板,不知道它在其他实现中如何工作,但尝试看看在它。您可以在保存对象之前和之后键入代码,这样您就可以修改 obj.date_sorted 然后保存模型。
Try this, it will hide datetime field from your form and automaticly set date when you post message:
Also, you can use save_model method:
I used this for admin panel and don't know how it works in other implementations, but try to look at it. You can type your code before saving object and after it, so you can modify obj.date_sorted and then save model.
models.DateTimeField
有两个属性:auto_now_add=True|False
和auto_now=True|False
。它们都会自动将字段设置为
editable=False
。使用
auto_now=True
设置每次字段更新时的当前日期时间。使用
auto_now_add=True
仅在第一次保存对象时设置当前时间。models.DateTimeField
has two attributes:auto_now_add=True|False
andauto_now=True|False
.Both of them will automatically make field as
editable=False
.Use
auto_now=True
to set current date-time each time field is updated.Use
auto_now_add=True
to set current time only the first time object is saved.