简体   繁体   中英

django custom form clean() raising error from clean_field()

I have created a custom form and need to override both of the clean_field() method and clean() method. Here is my code:

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?

If I save this form twice, and the username will be already exist in the second time, the clean_username method will raise an error, however, the clean() method still run without interruption.

So my question is, how can I stop calling clean() when error already raise by cleaned_xxx , if that is not possible, then how can I raised the error again which raised by clean_xxxx() in clean() method?

In your clean method, you can check whether username is in the cleaned_data dictionary.

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

You probably don't need the else statement. The user will see the error from the clean_username method so you don't need to create another one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM