[Fixed]-Django testing: Got an error creating the test database: database "database_name" already exists


When testing, Django creates a test database to work on so that your development database is not polluted. The error message says that Django is trying to create a test database named "database_name" and that this database already exists. You should check the tables of the database software you are using and check what is in database_name, it’s probably been created by mistake.

If you type yes, the database database_name will be deleted and it is unlikely that you will be able to recover the data. So try to understand what is going on first.

You should set the name of the test database in settings.py. There is a specific TEST dictionary in the DATABASE settings for this:


    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'mydatabaseuser',
        'NAME': 'mydatabase',
        'TEST': {
            'NAME': 'mytestdatabase',

By default, the prefix test_ is added to the name of your development database. You should check your settings.py to check what is going on.

From the docs:

The default test database names are created by prepending test_ to the value of each NAME in DATABASES. When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). The TEST dictionary in DATABASES offers a number of settings to configure your test database. For example, if you want to use a different database name, specify NAME in the TEST dictionary for any given database in DATABASES.


FWIW, in the event that you get such a warning when using the --keepdb argument such as

python manage.py test --keepdb [appname]

then this would typically mean that multiple instances of the Client were instantiated, perhaps one per test. The solution is to create one client for the test class and refer to it in all corresponding methods like so:

from django.test import TestCase, Client

class MyTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_one(self):
        response = self.client.get('/path/one/')
        # assertions

    def test_two(self):
        response = self.client.post('/path/two/', {'some': 'data'})
        # assertions

You could also (unverified) create a static client using the setUpClass class method.

Leave a comment