本文介绍了django覆盖表单clean方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当覆盖表单clean方法时,如何知道其在任何字段上的验证失败?例如在下面的表单中,如果我覆盖了干净的方法,如何知道窗体是否在任何字段上验证失败?
PersonForm(forms.Form):
title = Forms.CharField(max_length = 100)
first_name = Forms.CharField(max_length = 100)
surname = Forms.CharField(max_length =
password = Forms.CharField(max_length = 100)
def clean(self,value):
cleaning_data = self.cleaned_data
如果FORM已经失败的验证:
self.data ['password'] ='abc'
raise forms.ValidationError(您验证失败!)
ELSE:
return clean_data
谢谢
解决方案>
您可以检查是否有任何错误添加到错误dict:
def clean(self,value):
cleaning_data = self.cleaned_data
如果self._errors:
self.data ['password' ] ='abc'
raise forms.ValidationError(你验证失败!)
else:
返回clean_data
奖金!您可以检查特定字段的错误:
def clean(self,value):
cleaning_data = self.cleaned_data
如果self._errors和'title'在self._errors中:
raise forms.ValidationError(你称之为标题?!)
else:
返回cleaning_data
When overwriting a form clean method how do you know if its failed validation on any of the fields? e.g. in the form below if I overwrite the clean method how do I know if the form has failed validation on any of the fields?
class PersonForm(forms.Form):
title = Forms.CharField(max_length=100)
first_name = Forms.CharField(max_length=100)
surname = Forms.CharField(max_length=100)
password = Forms.CharField(max_length=100)
def clean(self, value):
cleaned_data = self.cleaned_data
IF THE FORM HAS FAILED VALIDATION:
self.data['password'] = 'abc'
raise forms.ValidationError("You have failed validation!")
ELSE:
return cleaned_data
Thanks
解决方案
You can check if any errors have been added to the error dict:
def clean(self, value):
cleaned_data = self.cleaned_data
if self._errors:
self.data['password'] = 'abc'
raise forms.ValidationError("You have failed validation!")
else:
return cleaned_data
BONUS! You can check for errors on specific fields:
def clean(self, value):
cleaned_data = self.cleaned_data
if self._errors and 'title' in self._errors:
raise forms.ValidationError("You call that a title?!")
else:
return cleaned_data
这篇关于django覆盖表单clean方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-15 07:40