0

如何不在 'required=False' 字段中调用 clean_ 方法?

表格.py

from django import forms

class userRegistrationForm(forms.Form):
    username = forms.CharField(
        max_length=30,
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput(),
    )

    email = forms.EmailField(  # If user fill this, django will call 'clean_email' method.
        required=False,  # But when user don't fill this, I don't want calling 'clean_email' method.
    )

    def clean_email(self):
        if 'email' in self.cleaned_data:
            try:
                User.objects.get(email=self.cleaned_data['email'])
            except ObjectDoesNotExist:
                return self.cleaned_data['email']
            else:
                raise forms.ValidationError('Wrong Email!')

用户可以填写“电子邮件”,无需填写“电子邮件”字段。

我应该怎么办?

4

1 回答 1

1

如果你有一个clean_field,无论你是否填充它都会被调用,因为这是由 django 内部调用的full_clean

如果提供了一些电子邮件,您似乎只想进行自定义验证。所以,你可以这样做:

def clean_email(self):
    email = self.cleaned_data['email']
    #If email was provided then only do validation
    if email:
        try:
            User.objects.get(email=self.cleaned_data['email'])
        except ObjectDoesNotExist:
            return email
        else:
            raise forms.ValidationError('Wrong Email!')
    return email
于 2013-04-24T04:45:11.737 回答