将自定义表单错误分配给django中的modelform中的字段

时间:2014-02-11 13:29:21

标签: django forms

我正在尝试将自定义表单错误分配给django中的模型中的字段,以便它出现“标准”错误,例如字段留空,具有相同的格式(由脆表单处理)

我的模型表单清洁方法如下所示:

def clean(self):
    cleaned_data = super(CreatorForm, self).clean()
    try:
        if cleaned_data['email'] != cleaned_data['re_email']:
            raise forms.ValidationError({'email': "Your emails don't match!"})
    except KeyError:
        pass
    return cleaned_data

在我的模板中,我显示表格/重新提交的表格,如下所示:

{{creator_form|crispy}}

如果可能的话,我希望错误出现在re_email字段下面(虽然目前我认为我有更好的运气在电子邮件字段下面。目前它出现在表单的顶部,未格式化。

对于re_email字段,尽管不是模型的一部分,但显示为将其留空的错误显示在re_email字段下方。如何将“附加”错误附加到字段,以便它们显示在它们下方/附近?

所有帮助表示感谢

1 个答案:

答案 0 :(得分:3)

要在特定字段上显示错误,您需要明确定义错误发生的字段,因为您要覆盖.clean()。以下是取自Django docs

的示例
class ContactForm(forms.Form):
    # Everything as before.
    ...

    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 and "help" not in subject:
            # We know these are not in self._errors now (see discussion
            # below).
            msg = u"Must put 'help' in subject when cc'ing yourself."
            self._errors["cc_myself"] = self.error_class([msg])
            self._errors["subject"] = self.error_class([msg])

            # These fields are no longer valid. Remove them from the
            # cleaned data.
            del cleaned_data["cc_myself"]
            del cleaned_data["subject"]

        # Always return the full collection of cleaned data.
        return cleaned_data