如何不在 '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!')
用户可以填写“电子邮件”,无需填写“电子邮件”字段。
我应该怎么办?