在Django模型形式中覆盖clean()方法时返回cleaned_data

Rob*_*Rob 4 python django django-forms

我需要以clean()Django模型形式覆盖该方法,以对输入的数据执行其他唯一性检查。

该页面提供了实现的详细信息:https : //docs.djangoproject.com/en/1.11/ref/forms/validation/复制在这里:

 def clean(self):
    cleaned_data = super(ContactForm, self).clean()
    cc_myself = cleaned_data.get("cc_myself")
    subject = cleaned_data.get("subject")

    if cc_myself and subject:
        # Only do something if both fields are valid so far.
        if "help" not in subject:
            raise forms.ValidationError(
                "Did not send for 'help' in the subject despite "
                "CC'ing yourself."
            )
Run Code Online (Sandbox Code Playgroud)

但是我很困惑为什么这个方法不在return cleaned_data函数的结尾?当然这是正确的做法吗?

Cof*_*orm 5

看一下django的_clean_form方法:

def _clean_form(self):
    try:
        cleaned_data = self.clean()
    except ValidationError as e:
        self.add_error(None, e)
    else:
        if cleaned_data is not None:
            self.cleaned_data = cleaned_data
Run Code Online (Sandbox Code Playgroud)

阅读表格doc 的最后一点尤其是ModelForm doc的这一点。

如果clean方法引发a ValidationError,则错误将添加到表单的错误中。如果该clean方法返回了任何内容且未引发任何错误,则表单将使用该cleaned_data属性为其属性。否则,它将保持其“旧”状态。

对于您而言,您的clean方法所做的就是验证表单的某个方面。


sch*_*tte 0

您感兴趣的示例是clean相关字段的方法的重写。这意味着它验证了涉及多个字段的逻辑。将此视为表单的clean方法。因此,在这种情况下您不想返回任何值。

\n\n

正如医生所说:

\n\n

“在实践中执行此操作时要小心,因为它可能会导致令人困惑的表单输出。我们\xe2\x80\x99正在展示此处的可能性,并让您和您的设计师来确定在您的特定情况下有效的方法。 ”

\n\n

这取决于您的具体情况,但根据我覆盖clean某一特定字段的经验,如果验证通过,您将希望返回它。再次强调,这仅适用于一个字段。

\n\n

这是文档中的另一个示例,但用于一个字段验证:

\n\n
def clean_recipients(self):\n    data = self.cleaned_data[\'recipients\']\n    if "fred@example.com" not in data:\n        raise forms.ValidationError("You have forgotten about Fred!")\n\n    # Always return a value to use as the new cleaned data, even if\n    # this method didn\'t change it.\n    return data\n
Run Code Online (Sandbox Code Playgroud)\n