django表单-从clean()引发特定字段验证错误 [英] django form - raising specific field validation error from clean()

查看:34
本文介绍了django表单-从clean()引发特定字段验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a validation check on a form which depends on more than one field, but it would be good to have the validation error show the user specifically which fields are causing the issue, rather than just an error message at the top of the form. (the form has many fields so it would be clearer to show specifically where the error is).

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

As a work around I tried to create the same validation in each of the relevant fields clean_field() method so the user would see the error next to those fields. However I only seem to be able to access that particular field from self.cleaned_data and not any other?

或者可以从 clean()方法的形式引发字段错误吗?

Alternatively is it possible to raise a field error from the forms clean() method?

尝试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):
          .....

推荐答案

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

If you want to access cleaned data for more than one field, you should use the clean method instead of clean_<field> method. The add_error() method allows you to assign an error to a particular field.

例如,要向 same_address 字段添加请在地址处指定时间错误消息,您可以这样做:

For example, to add the Please specify time at address error message to the same_address field, you would do:

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

请参阅

See the docs on validating fields that rely on each other for more info.

这篇关于django表单-从clean()引发特定字段验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆