django自定义表单clean()从clean_field()引发错误

时间:2016-09-26 15:35:57

标签: python django forms validation

我创建了一个自定义表单,需要覆盖clean_field()方法和clean()方法。这是我的代码:

class MyForm(forms.Form):
    username=forms.RegexField(regex=r'^1[34578]\d{9}$')
    code = forms.RegexField(regex=r'^\d{4}$')

    def clean_username(self):
        u = User.objects.filter(username=username)
        if u:
            raise forms.ValidationError('username already exist')
        return username

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        # How can I raise the field error here?

如果我将此表单保存两次,并且用户名将在第二次存在,则clean_username方法将引发错误,但clean()方法仍会在不中断的情况下运行。

所以我的问题是,如果错误已经由clean()引发,我怎么能停止调用cleaned_xxx,如果不可能,那么我怎样才能再次提出由{{1}引发的错误在clean_xxxx()方法中?

1 个答案:

答案 0 :(得分:1)

clean方法中,您可以检查username字典中是否有cleaned_data

def clean(self):
    cleaned_data = super(MyForm, self).clean()
    if 'username' in cleaned_data:
        # username was valid, safe to continue
        ...
    else:
        # raise an exception if you really want to

您可能不需要else语句。用户将看到clean_username方法中的错误,因此您无需再创建另一个错误。