How To Fix User Matching Query Does Not Exist Error In Django Unit Test

When I write and run the Django app models unit test, I meet an error like this django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. 


After some investigation, I find the reason for this error is because I get a User model object in my test function like below, the User model is located in Django default admin package django.contrib.auth.models.

You can read Django User Registration And Login Use Built-in Authorization ExampleHow To Manage Models In Django Admin Site to learn more.

from django.test import TestCase

from django.contrib.auth.models import User

class ModelTest(TestCase):

    def setUpClass(cls):

        # below code will fix AttributeError: type object 'Model Test' has no attribute 'cls_atomics' error.
        super(ModelTest, cls).setUpClass()

        # get Django authentication user object whose username is 'tom'.
        user = User.objects.get(username='tom')

But as the Django docs said, in the Django unit test, the model used database is not the real product database, it is a temporary database that is created when the unit test starts and destroyed after the unit test stop, so the User model object whose username is ‘tom’ does not exist during the unit test execution. Please refer to the Writing and running tests in Django The test database section.

So when the above test case class runs, the temporary created database does not has any User model data. So you should add user ‘tom’ in the test function first to save it to the temporary database, then get it to resolve the error like below.

# create a User model object in temporary database.
user = User(username='tom', password='tom')

# get employee user.
user = User.objects.get(username='tom')
print('Added user data : ')

In the ModeTest test case class’s setUpClass function, we add code super(ModelTest, cls).setUpClass() at the first line, this line of code is used to avoid AttributeError: type object ‘Model Test’ has no attribute ‘cls_atomics’ error.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.