Django:如果我不想调用 clean_() 方法,我可以这样做吗?
class myForm(forms.Form):
userId = forms.CharField(max_length=30, required=False,)
email = forms.EmailField(required=False,)
def clean_userId(self):
if 'userId' in self.cleaned_data:
if not re.search(r'^\w+$', self.cleaned_data['userId']):
raise forms.ValidationError('Invalid ID')
try:
User.objects.get(username=self.cleaned_data['userId'])
except ObjectDoesNotExist:
return self.cleaned_data['userId']
raise raise forms.ValidationError('Invalid ID')
else:
raise raise forms.ValidationError('Invalid ID')
有时,我想使用表单验证来仅验证“电子邮件”字段。
如下所示:
>>> form = myForm({'email':'abc@com'})
>>> form.cleaned_data['email']
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'myForm' object has no attribute 'cleaned_data'
>>> print form.errors
<ul class="errorlist"><li>workers<ul class="errorlist"><li>Invalid ID</li></ul>
有办法吗?