Ad

How To Check Unique While Update On Django

- 1 answer

I have successfully check validation of unique while user is registered, but during his profile update, how do I check the unique email during the update?

views.py

def UpdateProfile(request, user_id):
    data = UserModel.objects.get(pk=user_id)

    if request.method == 'POST':
        form = profileForm(request.POST, instance=data)
        if form.is_valid():
            print('dd')
    else:
        form = profileForm(instance=data)    
    context = {
        'data' : data,
        'form' : form
    }
    return render(request, 'profile_update.html', context)    

forms.py

class profileForm(forms.ModelForm):    
    name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'id' : "firstName" ,
                    'placeholder' : 'Enter Name', 'autofocus' : 'autofocus', 'value' : 12 }),validators=[validators.MinLengthValidator(5), validators.MaxLengthValidator(10)])
    email = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'id' : "inputEmail" ,
                    'placeholder' : 'Enter Email'}),validators=[validators.validate_email])

    username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'id' : "username" ,
                    'placeholder' : 'Enter Username'}),validators=[validators.MinLengthValidator(5), validators.MaxLengthValidator(8)])

    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'id' : "inputPassword" ,
                     'placeholder' : 'Enter Password'}),validators=[validators.MinLengthValidator(5), validators.MaxLengthValidator(8)])

    file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'class': 'form-control'}), required=False)    

    def clean(self):
        cleaned_data = self.cleaned_data
        email = cleaned_data.get('email')
        user_id = cleaned_data.get('user_id')
        print(user_id)
        uname = cleaned_data.get('username')
        print(UserModel.objects.filter(email__iexact=email))
        if UserModel.objects.filter(email__iexact=email) == True and UserModel.objects.filter(username__iexact=uname) == True:            
            # self._errors['email'] 
            raise forms.ValidationError({'email': ["Email is already exist",], 'username': ["Username is already exist",]})

        if UserModel.objects.filter(email__iexact=email) == True:            
            # self._errors['email'] 
            raise forms.ValidationError({'email': ["Email is already exist",]})

        # if UserModel.objects.filter(username__iexact=uname).exists() == True:            
        if UserModel.objects.filter(username__iexact=uname) == True:            
            # self._errors['email'] 
            raise forms.ValidationError({'username': ["Username is already exist",]})

        return self.cleaned_data     
    class Meta:
        model = UserModel
        fields = '__all__'

        labels = {
            "username": "uname"
        }
Ad

Answer

You can check unique email like this while updating the user

  def clean_email (self):
      email  = self.cleaned_data ['email']
      email_exists = User.objects.filter (email=email).exclude (pk=self.instance.pk) # excluding the current user from queryset
      if self.instance and self.instance.pk and not email_exists:
          return email 
      else :
          raise ValidationError ("email already exists")
Ad
source: stackoverflow.com
Ad