Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a Django user has a password set

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?

like image 840
Designer023 Avatar asked Jun 22 '13 11:06

Designer023


People also ask

How do I check my Django password?

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. So the current password of the user is, request. user. password, which we store in the currentpassword variable.

How do I find my Django username and password?

from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...

Is there a password field in Django?

Django provides a flexible password storage system and uses PBKDF2 by default. Those are the components used for storing a User's password, separated by the dollar-sign character and consist of: the hashing algorithm, the number of algorithm iterations (work factor), the random salt, and the resulting password hash.

How do I find my username and password matches the database values in Django?

You can't manually check the password. Because when you are creating a user, django is storing the user's password as a hash value in the database. Now if you are storing the raw password in your custom table which is myuser , it's not a good practice.


1 Answers

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.

like image 74
falsetru Avatar answered Sep 30 '22 06:09

falsetru