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

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

Django contrib auth models user doesnotexist User Matching Query Does Not Exist Error In Django Unit Test

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):

    @classmethod
    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')
      
        print(user)

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

django unit test test database section

So when above test case class run, the temporary created database do 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')
user.save()

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

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.

READ :   How To Add New Model Field To Exist Django Model

Leave a Reply

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.