0

如何在一个方法中验证空格、空格和整数。考虑我的 forms.py

class UserprofileForm(forms.ModelForm):
    class Meta:
        model = Userprofile
        fields=['username1','phonenumber1','username1','phonenumber1']

如何验证这一点。

  • 所有字段都不是强制性的。
  • 但是如果输入了 username1 或 username2 而没有分别输入 phonenumber1 或 phonenumber2 ,它应该会引发验证错误。
  • 如果输入任何空格,它也应该引发验证错误。
  • 有什么方法可以在views.py中使用strip()来验证空格。

谁能告诉我如何实现这一点。请给我一个如何执行的例子。

谢谢

4

2 回答 2

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 文档:

https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

于 2013-05-23T05:29:02.997 回答
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

您可以检查此验证方法。感恩

于 2013-05-23T05:22:19.953 回答