How to Check a User's Password in Django


In this article, we show how to check a user's password in Django.

Django does have a login() function that allows a user to log in, once the username and password are supplied.

However, checking the password alone may be important, such as if you are creating a 'Change Password' page for your website. Usually on a 'Change Password' form, the user specifies the old password and then the new password twice for confirmation.

In order to check whether the user supplies the correct password (the old password), we need to check the password. So for a case like this, we need to be able to know how to check a password in Django.

Since Django hashes passwords using the pbkdf2_sha256 algorithm, you cannot simply take the password from the database and compare it with the plaintext password. It won't work. What you can do is use the built-in Django check_password() function to check whether the plaintext password is equivalent to the hashed password.

This is what we'll do in this article.

Above is code from the file.

In order to use the built-in Django check_password() function, we need to import it, which is shown in the first line of code.

We then have a function called changepassword()

So the current password of the user is, request.user.password, which we store in the currentpassword variable. Remember that this is the hashed password.

We then bring in the ChangePasswordform, which is the form that allows the user to change his/her password. This form has 3 fields, old password, new password, and confirm new password.

The variable, currentpasswordentered, is the old password which the user has entered. We want to check this password to make sure it is the right password. We cannot simply use an if statement to check if currentpassword == currentpasswordentered, because one is a hashed password and the other is a plaintext password. The comparison will not work. Instead we use the built-in Django check_password() function.

The check_password function takes in 2 arguments. The first argument is the plaintext password. This is what the user enters in the form. The second arugment is the current hashed password.

The check_password will hash the plaintext password and check to see whether it is equal to the current hashed password.

This functions returns a boolean value, either True (if the passwords are equal) or False(if the passwords are not equal).

In the code above, we store this boolean value in the variable, matchcheck.

If the passwords are equal, matchcheck will be True. If not, matchcheck will be False.

And this is how we can check and verify a user's password in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...