The Test Database in Django

I have a Django project with the following DB config:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'feedread',
        'USER': 'feedread',
        'PASSWORD': 'feedread',
        'HOST': os.getenv('PG_HOST') or 'db',
        'PORT': '5432',
    }
}

However, locally in development I am using docker-compose so the db listens at the db hostname. I’ve looked through the Django docs and it seems like there is no way to specify a different hostname during testing.

I am using os.getenv('PG_HOST') where PG_HOST is set to localhost but it feels like a hack. The alternative would be to add 127.0.0.1 db to /etc/hosts but that also feels like a hack.

Has anyone done something like this before? Is there really no way to have a different hostname for testing?

When developing with Django it’s good practice to have several settings files in a settings directory like so:

You may want a ci.py file for use in a CI environment.

Each settings file can have the correct db connection settings for each environment.

You then run in each environment by specifying the relevant settings, e.g:

python manage.py runserver --settings=yourapp.settings.local

If you don’t want to manually specify this every time you can set the DJANGO_SETTINGS_MODULE and PYTHONPATH env vars in each environment.

1 Like

Thank you tom this is really helpful!