elethan
elethan

Reputation: 17003

Django authenticate function returning None when passed existing username and password

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='[email protected]', 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?

Upvotes: 0

Views: 547

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600026

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.

Upvotes: 4

user2390182
user2390182

Reputation: 73498

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='[email protected]', password='whatever')
>>> user.set_password('abc')  # takes plain text and stores the hash

>>> user.check_password('abc')
True

Upvotes: 1

Related Questions