pythondjangodjango-1.11

Django's authenticate method returns 'None' for a an already saved User


Settings.py

AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
)

Tests.py which has the code triggering the error

class LoginTest(TestCase):

    def test_can_redirect_to_user_page_if_authentificated(self):
        test_user = User(username='foo', password='bar', first_name='Testy', last_name='McTestingTon', email='testy@email.com', is_active=True)
        test_user.save()
        current_user = authenticate(username=test_user.username, password=test_user.password)
        print(current_user)

        response = self.client.post('/login', data = {'username' : current_user.username, 'password' : current.password})
        self.assertEqual(response.url, '/users/Testy')

current_user is always returned as None

I've tried numerous advices from other posts here on SO but authenticate still returns None for a user whose is_active I've explicitly set to True and with the ModelBackend added to my settings.py.


Solution

  • You should use create_user to create a user, saving a User object directly will not encrypt the password so will never authenticate

    test_user = User.objects.create_user(...)