Django DateTimeField 在未编辑时变为 null

发布于 2024-11-29 07:29:06 字数 574 浏览 2 评论 0原文

基本上我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对你的占有欲 2024-12-06 07:29:06

试试这个,它会隐藏表单中的日期时间字段,并在您发布消息时自动设置日期:

date_sorted = models.DateTimeField(auto_now=True)

另外,您可以使用 save_model 方法:

def save_model(self, request, obj, form, change):
    super(MessageAdmin, self).save_model(request, obj, form, change)

我将其用于管理面板,不知道它在其他实现中如何工作,但尝试看看在它。您可以在保存对象之前和之后键入代码,这样您就可以修改 obj.date_sorted 然后保存模型。

Try this, it will hide datetime field from your form and automaticly set date when you post message:

date_sorted = models.DateTimeField(auto_now=True)

Also, you can use save_model method:

def save_model(self, request, obj, form, change):
    super(MessageAdmin, self).save_model(request, obj, form, change)

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.

执手闯天涯 2024-12-06 07:29:06

models.DateTimeField 有两个属性:auto_now_add=True|Falseauto_now=True|False
它们都会自动将字段设置为 editable=False
使用 auto_now=True 设置每次字段更新时的当前日期时间。
使用auto_now_add=True仅在第一次保存对象时设置当前时间。

models.DateTimeField has two attributes: auto_now_add=True|False and auto_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文