18

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?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Designer023
  • 1,902
  • 1
  • 26
  • 43
  • 1
    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? – karthikr Jun 22 '13 at 11:31
  • Yes it prints out the password. I din't think of doing that. I think I have now found the solution from falsetru :) – Designer023 Jun 22 '13 at 11:43

2 Answers2

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    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 set – doeke Mar 06 '19 at 12:51
  • @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. – falsetru Mar 06 '19 at 14:15
  • In my project I simply changed it to `a.password and a.has_usable_password()` – doeke Mar 07 '19 at 15:19
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

Never367
  • 1
  • 1