Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

User.last_login not populating as expected in Django test

Why is user.last_login None in the following test:

from django.test import TestCase, Client


class TestModels(TestCase):
    @classmethod
    def setUpTestData(self):
        self.user = User.objects.create(
            username="testUser", password="testPassword"
        )
        self.auth_client = Client()
        self.auth_client.login(username="testUser", password="testPassword")

    def test_user_last_login(self):
        user = User.objects.get(id=self.user.id)  # pull the latest data
        print(user.last_login). # <-- this is None, why?!
        self.assertIsNotNone(user.last_login)

I am clearly logging in, then querying the user from the database to refresh the data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

last_login is not updated because you are not logging in. All User passwords are encrypted, so when you are creating user like that, his password will be in plain text and you won’t be able to authenticate by it. To create User with enrypted password, change

self.user = User.objects.create(
            username="testUser", password="testPassword"
        )

to

self.user = User.objects.create_user(
            username="testUser", password="testPassword"
        )

and your tests will pass

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading