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?

4

1 回答 1

39

使用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

更新

根据文档,has_usable_password改变的行为。

在 Django 2.1 中更改:

在旧版本中,如果密码为 None 或空字符串,或者密码使用不在 PASSWORD_HASHERS 设置中的哈希,这也会返回 False。这种行为被认为是一个错误,因为它会阻止具​​有此类密码的用户请求重置密码。

于 2013-06-22T11:36:09.373 回答