Python django自定义表单clean()从clean_字段()引发错误
我已经创建了一个自定义表单,需要重写Python django自定义表单clean()从clean_字段()引发错误,python,django,forms,validation,Python,Django,Forms,Validation,我已经创建了一个自定义表单,需要重写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(usernam
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()
方法仍会无中断地运行
所以我的问题是,当
clean\u xxx
已经引发错误时,我如何停止调用clean()
,如果这不可能,那么我如何在clean()
方法中再次引发clean\u xxxx()
引发的错误?在clean
方法中,您可以检查用户名
是否在数据字典中
def clean(self):
cleaned_data = super(MyForm, self).clean()
if 'username' in cleaned_data:
# username was valid, safe to continue
...
else:
# raise an exception if you really want to
您可能不需要else语句。用户将从clean_username
方法中看到错误,因此您无需再创建一个。感谢您抽出时间,非常感谢您的回答。