ModelForm无错误验证

ModelForm无错误验证

本文介绍了Django ModelForm无错误验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我一直在盯着这几个小时试图弄清楚发生了什么,没有效果。
我试图使用'instance'关键字创建一个ModelForm来传递一个现有的模型实例,然后保存它。
这是ModelForm(在我试图找出这个问题的原因的时候,从原文中大大删除了):

 类TempRuleFieldForm(ModelForm):
class Meta:
model = RuleField

这里是我正在运行的代码:

 >>> m = RuleField.objects.get(pk = 1)
>>> f = TempRuleFieldForm(instance = m)
>>> f.is_valid()
False

模型对象( m 以上)是有效的,它保存不错,但表单将不会验证。现在,据我所知,这段代码与Django文档的例子相同:,虽然显然我错过了一些东西。我非常感谢一些新鲜的眼睛告诉我我有什么错误。



谢谢

解决方案

请注意,您的链接不调用 f.is_valid(),它只是直接保存。这可能有点误导。要点是实例化一个只有一个实例参数但没有数据的表单 / code>不将绑定到数据,因此表单无效。你会看到 f.is_bound 是False。



在幕后, instance 与传递初始化数据完全一样,文档注释仅用于初始显示数据,不用于保存。您可能会从阅读获益。


Ok, I have been staring at this for hours trying to figure out what's going on, to no avail.I am trying to create a ModelForm using the 'instance' keyword to pass it an existing model instance and then save it.Here is the ModelForm (stripped considerably from the original in my attempts to identify the cause of this problem):

class TempRuleFieldForm(ModelForm):
    class Meta:
        model = RuleField

and here is the code I'm running:

>>> m = RuleField.objects.get(pk=1)
>>> f = TempRuleFieldForm(instance=m)
>>> f.is_valid()
False

The model object (m above) is valid and it saves just fine, but the form will not validate. Now, as far as I can tell, this code is identical to the Django docs example found here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method, though obviously I am missing something. I would greatly appreciate some fresh eyes to tell me what I've got wrong.

Thanks

解决方案

Note that your link doesn't call f.is_valid(), it just saves directly. This is potentially a bit misleading.

The point is that instantiating a form with just an instance parameter but no data does not bind it to data, and the form is therefore not valid. You will see that f.is_bound is False.

Behind the scenes, instance is really just the same as passing initial data, which as the docs note is only used to display the data initially and is not used for saving. You would probably benefit from reading the notes on bound and unbound forms.

这篇关于Django ModelForm无错误验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:35