[Fixed]-Checking if a Django user has a password set

40👍

Use user.has_usable_password

>>> a = User.objects.create_user('user1', 'user1@example.com')
>>> b = User.objects.create_user('user2', 'user2@example.com', password='secret')
>>> a.has_usable_password()
False
>>> b.has_usable_password()
True

UPDATE:

According to the documentation, the behavior of the has_usable_password changed.

Changed in Django 2.1:

In older versions, this also returns False if the password is None or an empty string, or if the password uses a hasher that’s not in the PASSWORD_HASHERS setting. That behavior is considered a bug as it prevents users with such passwords from requesting a password reset.

0👍

In new version Django you can use user.has_usable_password() with user.set_unusable_password().
Also you can use user.has_usable_password in django template.

https://docs.djangoproject.com/en/4.0/ref/contrib/auth/#django.contrib.auth.models.User.set_unusable_password

Leave a comment