如何在单个方法中验证空格,空格和整数。考虑我的forms.py
class UserprofileForm(forms.ModelForm):
class Meta:
model = Userprofile
fields=['username1','phonenumber1','username1','phonenumber1']
如何验证这一点。
任何人都可以告诉我们如何实现这一目标。请举例说明如何执行。
谢谢
答案 0 :(得分:1)
您可以使用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 Doc:
答案 1 :(得分:0)
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
您可以查看此验证方法。 thnaks