首页 > 解决方案 > 如何检查扩展用户模型中的重复项

问题描述

模型 - -

class UserProfile(models.Model):

      user = models.OneToOneField(User,on_delete=models.CASCADE)
      Mobile =models.CharField(max_length=15,default="")


      def __str__(self):


            return self.user.username

形式 - -

class UserProfileForm(forms.ModelForm):

      Mobile = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myinput', 'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}),min_length=10, max_length= 15, required =True ,validators = [clean_phone, ])

      class Meta:

            model = UserProfile
            fields=('Mobile',)
      def __init__(self, *args, **kwargs):
          super(UserProfileForm, self).__init__(*args, **kwargs)
          self.fields['Mobile'].widget.attrs.update({'class' : 'myinput' ,'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '})

看法 - -

#  signup form 
def signup (request):

    if request.method =="POST":
        form = signupForm(request.POST or None)
        userprofile =UserProfileForm(request.POST or None)

        if form.is_valid() and userprofile.is_valid():

            try: 

                First_Name= form.cleaned_data['Name']
                email= form.cleaned_data['email']
                password= form.cleaned_data['password']
                re_password= form.cleaned_data['re_password']
                mobile= userprofile.cleaned_data['Mobile']
                print(User.userprofile)
                if User.objects.filter(username=email).exists() or User.objects.filter(email=email).exists():

                   print("Email id is already taken")

                elif User.userprofile.objects.filter(mobile=mobile).exsist():

                      print("Mobile Number already taken ")  

我想知道用户配置文件中是否已经有手机号码

标签: djangodjango-modelsextending

解决方案


我会将唯一检查放在表单上而不是视图中。

class UserProfileForm(forms.ModelForm):

      Mobile = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myinput', 'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '}),min_length=10, max_length= 15, required =True ,validators = [clean_phone, ])

      class Meta:
            model = UserProfile
            fields = ('Mobile',)

      def __init__(self, *args, **kwargs):
          super(UserProfileForm, self).__init__(*args, **kwargs)
          self.fields['Mobile'].widget.attrs.update({'class' : 'myinput' ,'placeholder':'Mobile Number','title':'Please Enter Phone Number Without Country Code, Eg:9999999999 '})

      def clean_mobile(self, data):
          value = data['Mobile']
          existing_profiles = UserProfile.objects.filter(mobile=value)

          if self.instance and self.instance.pk:
              existing_profiles = existing_profiles.exclude(pk=self.instance.pk)
          if existing_profiles.exists():
              raise forms.ValidationError("This phone number has already been taken.")
          return value

推荐阅读