测试 Django ModelForm 是否有实例 [英] Test if Django ModelForm has instance
问题描述
如果我进入编辑表单,我想显示一条警告消息,如果我进入 Django ModelForm 的创建表单,我想隐藏它.
I would like to display a warning message if I am into an editing form and hide it if I am in a creation form of a Django ModelForm.
form.is_bound
告诉我之前是否填充了表单,但如何测试 ModelForm 是否使用现有实例设置?
form.is_bound
tell me if the form was previously populated but how to test if the ModelForm was set with an existing instance ?
我试过这个 hasattr(form.instance, 'pk')
但这是正确的方法吗?
I tried this hasattr(form.instance, 'pk')
but is it the right way to do so ?
干杯,
纳蒂姆
推荐答案
尝试检查 form.instance.pk
是否为 None
.
Try checking if form.instance.pk
is None
.
hasattr(form.instance, 'pk')
将始终返回 True
,因为每个模型实例都有一个 pk
字段,即使它尚未保存到数据库中.
hasattr(form.instance, 'pk')
will always return True
, because every model instance has a pk
field, even when it has not yet been saved to the database.
正如@Paullo 在评论中指出的那样,如果您手动定义主键并指定默认值,则这将不起作用,例如default=uuid.uuid4
.
As pointed out by @Paullo in the comments, this will not work if you manually define your primary key and specify a default, e.g. default=uuid.uuid4
.
这篇关于测试 Django ModelForm 是否有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!