在我的一个 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/