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?
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.
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 ...
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With