I am having trouble getting the Django authenticate
function to work the way I expect. When I create a new user and try to authenticate in the manner described in the documentation , the authenticate()
function returns None
. I have seen many posts about " authenticate
not working", but none of the solutions work for me. Here is a demonstration:
In [34]: user = User.objects.create(username='fakeuser', email='fake@fakemail.com', password='abc')
In [35]: user
Out[35]: <User: fakeuser>
In [39]: auth_user = authenticate(username='fakeuser', password='abc')
In [40]: print(auth_user)
None
It is my understanding that authenticate()
in this case should return an object that I can then pass to the login()
function to log the user in, but I get None
instead. What am I doing wrong?
You're creating the user wrong. Django will always hash the password passed to authenticate, but you're creating the user with a plain text password.
Use create_user
instead.
Django's password hashing is the problem, as Daniel Rosemann has stated in his answer. You can also solve this in two steps:
>>> user = User.objects.create(username='fakeuser', email='fake@fakemail.com', password='whatever')
>>> user.set_password('abc') # takes plain text and stores the hash
>>> user.check_password('abc')
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.