如何在'required = False'字段中调用clean_ <fieldname>方法?</fieldname>

时间:2013-04-24 04:38:02

标签: django python-2.7 django-forms django-1.4

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

forms.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!')

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

我该怎么办?

1 个答案:

答案 0 :(得分: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