【发布时间】:2016-09-26 15:35:56
【问题描述】:
我创建了一个自定义表单,需要同时覆盖clean_field() 方法和clean() 方法。这是我的代码:
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?
如果我保存此表单两次,并且第二次用户名已经存在,clean_username 方法会报错,但是clean() 方法仍然运行而不会中断。
所以我的问题是,当cleaned_xxx 已经引发错误时,我该如何停止调用clean(),如果这是不可能的,那么我该如何再次引发clean_xxxx() 在clean() 方法中引发的错误?
【问题讨论】:
标签: python django forms validation