[Answer]-Django, update profile, check if email is unique(exclude logged in user's email)

1👍

I had a similar problem when I was trying to update users’ email. My problem was because I was trying to use the same form to update and to create an user. If you have a form that checks if the email is used you cannot use it to update user because it will fails like it’s happening now. When it is an update I recommend you to use another form (updateUserForm) and then the def clean_email function just have to check that the new email is not used for other users, something like

if not User.objects.filter(email=email):
      #Then there is no other users with the new email
      #Do whatever you have to do, return true or update user
else:
     raise forms.ValidationError('This email address is already in use.'
                                    'Please supply a different email address.')

EDIT (update user info):

To change the email of some user you have to follow 3 steps. Load the user, change the attributes you want and then save:

existing_user = User.objects.get(id=1)  #You have to change this for your query or user    
existing_user.email = 'new@email.com'    
existing_user.save()

Obviously nobody has to be using ‘new@email.com’

0👍

check this out

class UserCreationEmailForm(UserCreationForm):

email = forms.EmailField()

class Meta:
        model = User
        fields = ('username', 'email')

def clean_email(self):
        # Check that email is not duplicate
        username = self.cleaned_data["username"]
        email = self.cleaned_data["email"]
        users = User.objects.filter(email__iexact=email).exclude(username__iexact=username)
        if users:
            raise forms.ValidationError('A user with that email already exists.')
        return email.lower()

Leave a comment