Checking if a Django user has a password set
Asked Answered
Y

2

19

I setup if statement to see if the current user has a password set. For some reason it just won't work. I have tried:

{% if not user.password %}
{% if user.password == None %}
{% if user.password is None %}

I have 2 user accounts (different browsers open), one with a password in one, and one without in the other. When I use the statements above I get the same showing in both browsers. What am I doing wrong?

Ytterbia answered 22/6, 2013 at 11:27 Comment(2)
if you do {{user.password}} does it print in the browser correctly ? Also, you probably want {{request.user.password}} - Are you sending a user object from the context?Deflate
Yes it prints out the password. I din't think of doing that. I think I have now found the solution from falsetru :)Ytterbia
R
41

Use user.has_usable_password

>>> a = User.objects.create_user('user1', '[email protected]')
>>> b = User.objects.create_user('user2', '[email protected]', 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.

Recalcitrate answered 22/6, 2013 at 11:36 Comment(3)
has_usable_password() was changed in Django 2.1: no longer returns False if the password is None or an empty string. So I think you now want to also test if user.password is setClipped
@doeke, Thank you for the information. I added note from django documentation. But I didn't change the code in the answer. Please suggest edit, I'll review it later. Thank you.Recalcitrate
In my project I simply changed it to a.password and a.has_usable_password()Clipped
S
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

Sherlocke answered 13/6, 2022 at 20:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.