如何在单个method.Consider my forms.py中验证空白、空空间和整数
class UserprofileForm(forms.ModelForm):
class Meta:
model = Userprofile
fields=['username1','phonenumber1','username1','phonenumber1']如何验证这一点。
有人能告诉我如何实现this.Please吗?给我一个如何执行的例子。
谢谢
发布于 2013-05-23 05:29:02
您可以使用clean()方法在其中执行验证逻辑:
class UserprofileForm(forms.ModelForm):
class Meta:
model = Userprofile
fields=['username1','phonenumber1','username1','phonenumber1']
def clean(self):
# do your validation here, such as
cleaned_data = super(UserprofileForm, self).clean()
username1 = cleaned_data.get("username1")
username2 = cleaned_data.get("username2")
phonenumber1 = cleaned_data.get("phonenumber1")
phonenumber2 = cleaned_data.get("phonenumber2")
if (
((username1 and not username1.isspace()) and not phonenumber1) or
((username2 and not username2.isspace()) and not phonenumber2) or
((not username1 or username1.isspace()) and phonenumber1 is not None) or
((not username2 or username2.isspace()) and phonenumber2 is not None)
):
raise forms.ValidationError("Name and phone number required.")
return cleaned_data您可以参考Django文档:
发布于 2013-05-23 05:22:19
class UserprofileForm(forms.ModelForm):
class Meta:
model = Userprofile
fields=['username1','phonenumber1','username2','phonenumber2']
def clean(self):
if 'username1' in self.cleaned_data and 'phonenumber1' in self.cleaned_data:
if not (self.cleaned_data['username1'] and self.cleaned_data['phonenumber1']):
raise forms.ValidationError("You must enter both username1 and phonenumber1")
if 'username2' in self.cleaned_data and 'phonenumber2' in self.cleaned_data:
if not (self.cleaned_data['username2'] and self.cleaned_data['phonenumber2']):
raise forms.ValidationError("You must enter both username2 and phonenumber2")
return self.cleaned_data您可以检查此验证方法。萨纳克斯
https://stackoverflow.com/questions/16706006
复制相似问题