Home > OS >  updating user with same email address, gives email already exists error
updating user with same email address, gives email already exists error

Time:10-21

I am trying to update user fields but it returns email already exists error when I try to update it with the same email address.

@login_required
def user_profile(request, id):
  if request.user.id == int(id):
    if request.method == "POST":
      user = Account.objects.get(pk=request.user.pk)
      form = UserProfileUpdateForm(request.POST, user=user)

      if form.is_valid():
        form.save()
        messages.success(request, mark_safe("UPDATE: <br> your profile is updated"))

        context = {
          "form": form
        }

        return render(request, "accounts/user_profile.html", context)

      else:
       #...
    else:
      #...
  else:
    return redirect("not_found")

and forms.py

class UserProfileUpdateForm(forms.ModelForm):

  class Meta:
    model = Account
    fields = ["first_name", "last_name", "first_name_kana", "last_name_kana",
              "post_code", "city", "address", "building",
              "tel", "sex", "occupation",
              "year", "month", "day",
              "parent_name", "parent_name_kana",
              "year", "month", "day",
              "school_type",
              "school_name", "student_id",
              "email"]

  def __init__(self, *args, **kwargs):
    now = datetime.datetime.now()
    user = kwargs.pop("user")

    super(UserProfileUpdateForm, self).__init__(*args, **kwargs)

    # widget settings
   

What is the right way to update user fields with the same email address.

CodePudding user response:

You can exclude current user from the queryset while updating the user.

class UserProfileUpdateForm(forms.ModelForm):

  class Meta:
    model = Account
    fields = [....]

  def clean_email(self):
      email = self.cleaned_data.get("email")
      if Account.objects.filter(email=email).exclude(pk=self.instance.pk).exists():
          raise forms.ValidationError("Email Already Exists")
      return email
  • Related