Password Hash Mismatch on Login After Registration in Django

After registering a new user in Django, I’m unable to log in. The user’s data is saved in the database, but when trying to log in, the message “Please enter a correct username and password” appears. I checked the password hash in the database and noticed that it differs from the hash generated during the login attempt. I can’t understand why this is happening.

Here’s my code for saving the password:

		
# views.py def register(request): if request.method == 'POST': user_form = UserCreateForm(request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() return redirect('/login/')

Vincent Dupont

7 months ago

2 answers

82 views

Rating

06
Answer

Answers

Nicolas Dubois

7 months ago

1 comment

Rating

00

The UserCreationForm already calls the set_password method internally. Therefore, calling user.set_password(user.password) again in your view results in the password being hashed twice. This double hashing causes the password stored in the database to differ from the hash generated during the login attempt, leading to the mismatch error.

To fix the issue, remove the set_password call from your view. Here's the corrected code:

		
def register(request): if request.method == 'POST': user_form = UserCreateForm(request.POST) if user_form.is_valid(): user = user_form.save() # Removed set_password return redirect('/login/')

Reply

    Vincent Dupont

    7 months ago

    Rating

    00

    Thank you! The login now works correctly, and the password hash matches.

    Reply