【问题标题】:Assigning a custom form error to a field in a modelform in django将自定义表单错误分配给 django 中的模型表单中的字段
【发布时间】:2014-03-09 07:41:21
【问题描述】:

我正在尝试将自定义表单错误分配给 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 字段下方。如何将错误“附加”到字段,以便它们显示在它们下方/附近?

感谢所有帮助

【问题讨论】:

    标签: django forms


    【解决方案1】:

    要在特定字段上显示错误,您需要明确定义错误发生的字段,因为您要覆盖 .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
    

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      相关资源
      最近更新 更多