测试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 ?
Cheers,
Natim
推荐答案
尝试检查 form.instance.pk
是无
。
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.
这篇关于测试Django ModelForm是否有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!