django表单 - 从clean()中提出特定的字段验证错误

Yun*_*nti 2 django django-forms

我对表单进行了验证检查,该表单依赖于多个字段,但最好让验证错误向用户显示哪些字段导致问题,而不仅仅是表单顶部的错误消息.(表单有很多字段,因此更清楚地显示错误的位置).

作为一种解决方法,我尝试在每个相关字段clean_field()方法中创建相同的验证,以便用户在这些字段旁边看到错误.但是,我似乎只能访问该特定字段self.cleaned_data而不是其他任何字段?

或者可以从表单clean()方法引发字段错误?

尝试1:

   def clean_supply_months(self):
        if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
            raise forms.ValidationError('Please specify time at address if less than 3 years.')

    def clean_supply_years(self):
        if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_years'):
            raise forms.ValidationError('Please specify time at address if less than 3 years.')

    def clean_same_address(self):
          .....
Run Code Online (Sandbox Code Playgroud)

Ala*_*air 9

如果要访问多个字段的已清理数据,则应使用该clean方法而不是clean_<field>方法.该add_error()方法允许您将错误分配给特定字段.

例如,要将" 请指定时间地址"错误消息添加到same_address字段,您可以执行以下操作:

def clean(self):
    cleaned_data = super(ContactForm, self).clean()
    if not self.cleaned_data.get('same_address') and not self.cleaned_data.get('supply_months'):
        self.add_error('same_address', "Please specify time at address if less than 3 years.")
    return cleaned_data
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅有关验证彼此依赖的字段的文档.