python - 如何处理 django 表单中的 'auto-now' 字段?

标签 python django postgresql python-3.x django-1.8

在我的一个 django 模型中,我有一个这样的字段:

modified = models.DateTimeField(auto_now=True)

我想,当为这个模型创建 ModelForm 时,我可以跳过这个字段,Django 会自动填充它。

我的模型表单:

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
        fields = ['text', 'name', 'description'] # notice - modified field not included -
            # should not be shown to the user

但是,即使它没有出现在表单中,在提交时,在创建新对象时,我遇到了异常:

IntegrityError at /url/ - null value in column "modified" violates not-null constraint

我怎样才能做到这一点?

最佳答案

在这种情况下,auto_now 字段不会自动填充。

您需要使用auto_add_now,因此字段定义如下所示:

modified = models.DateTimeField(auto_now_add=True)

然后,如果该字段未显示,django 将自动添加日期。

关于python - 如何处理 django 表单中的 'auto-now' 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647982/

相关文章:

sql - 为什么我们使用 `As foo (geom)` 而不是 `As geom`

php - 在 postgres 数据库上使用 php 选择一个带有 & 符号的字符串

python - 如何使用 matplotlib 绘制 collections.Counter 直方图?

python - 如何移动绿色字符以在python中使用onkey?

django - 在 Django Mezzanine 中,如何对可以在页面树中的不同位置添加哪些自定义定义页面实现限制?

mysql - 我们应该从 MySQL 转换到 PostgreSQL 吗?

python - openerp中如何将数据存储到动态字段?

python - 如何使用编译器标志重建 tensorflow?

Django friend 作为多对多字段 - 更好地在字段中存储用户或用户配置文件( self )?

python - 错误 : The 'elasticsearch' backend requires the installation of 'requests' . 如何修复?