Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

ImproperlyConfigured: settings.DATABASES is improperly configured (Django): how to fix it

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. means Django has no database engine, so it fell back to a dummy backend that fails on the first query. Usually DATABASES is built from a DATABASE_URL that is not set, or set but empty, where the command runs, and dj-database-url returned an empty dictionary. Set DATABASE_URL, or give config() a default, and check it in the same environment.

By Livops team, the people who build and run LivopsUpdated

The app starts, then the first page that touches the database, or manage.py migrate, stops with this at the end of the traceback:

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

Django has no database engine to use. After a deploy that almost always means DATABASES is built from a DATABASE_URL that the process running the command does not have. This page explains when Django raises it, lists the causes from the most common, shows a safe default for DATABASES, and says where DATABASE_URL comes from on Livops. For the whole production setup of a Django app, see Django hosting.

What does the error mean?

DATABASES defaults to an empty dictionary, and it must configure a default database[1]. Each database’s ENGINE defaults to an empty string[1]. When Django sets up its connections, it replaces an empty DATABASES, an empty default entry, or an ENGINE that is empty, missing or just django.db.backends. with django.db.backends.dummy[3].

The dummy backend exists for exactly this case: Django uses it when ENGINE is empty, and every method that would do something with the database raises this ImproperlyConfigured[2]. Opening a connection, running a cursor, committing, listing tables, dbshell: all of them end in the same message[2].

That is why the error shows up late. Importing settings.py works. runserver checks for unapplied migrations at start, but it catches this exception and skips the check, with the comment “No databases are configured (or the dummy one)”[4], so the server comes up quietly. The first request that uses the ORM, a session or a login then answers 500 with this traceback. migrate fails at once, because it has to read the database.

A related message has its own cause: You must define a 'default' database. means DATABASES has other aliases but none called default[3].

Causes, most common first

1. DATABASE_URL is not set where the command runs

The usual settings.py reads the database from one variable with dj-database-url, as its README shows[7]:

import dj_database_url

DATABASES = {
    "default": dj_database_url.config(conn_max_age=600, conn_health_checks=True),
}

config() reads DATABASE_URL by default[7]. When the variable is not set and no default is given, it logs No DATABASE_URL environment variable set, and so no databases setup and returns an empty dictionary[8]. DATABASES becomes {"default": {}}, Django swaps in the dummy backend[3], and the first query raises this error.

The warning comes first, so look above the traceback for it. On your machine the variable comes from your shell or a .env file; on the server only the variables set there exist.

Fix: set DATABASE_URL in the environment of the process that runs Django, under exactly that name, and restart it. The URL names the engine by its scheme: postgres://, postgresql:// and pgsql:// all map to django.db.backends.postgresql[8]. Special characters in the password must be URL-encoded, # as %23 for example, or parse raises a ValueError[7].

If you use django-environ instead, a missing variable fails earlier and says so: env.db() raises ImproperlyConfigured with Set the DATABASE_URL environment variable when no default is given[9].

2. DATABASE_URL is set, but empty

A .env line DATABASE_URL= or a variable saved with no value is set, not missing. dj-database-url’s README says that if the selected variable is set to an empty string, config() returns an empty dictionary instead of using the default URL[7]. In the code, an empty string is not a URL to parse, so the function falls through to return {}[8]. This is the case where adding a default= seems to change nothing.

Fix: delete the empty variable, or give it a real URL. Check with the same environment the app has:

python -c "import os; print(repr(os.environ.get('DATABASE_URL')))"

None means not set (cause 1), '' means set but empty (this cause).

3. DATABASES is empty for the settings module that runs

DATABASES defaults to {}[1], and Django turns an empty one into the dummy backend[3]. A project that splits settings into base.py, dev.py and production.py hits this when only dev.py defines DATABASES and the server loads production.py. Check which module and engine Django really uses:

python manage.py shell -c "from django.conf import settings; from django.db import connection; print(settings.SETTINGS_MODULE, connection.settings_dict['ENGINE'])"

This opens no connection, so it works even when the engine is wrong. django.db.backends.dummy in the output confirms this error before any query runs.

4. ENGINE is built from a variable

Hand-written settings sometimes assemble the engine:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends." + os.environ.get("DB_ENGINE", ""),
        "NAME": os.environ.get("DB_NAME", ""),
    }
}

Without DB_ENGINE the value is django.db.backends., and "ENGINE": os.environ.get("DB_ENGINE") gives None. Django treats both as no engine at all and loads the dummy backend[3]. Set the variable, or write the engine out in full, for example django.db.backends.postgresql[1].

5. The variable exists when the app runs, but not when the build runs

Build steps import your settings too, and a build environment often has no database and no DATABASE_URL. Which steps fail depends on what they do:

  • migrate in a build step, such as a RUN python manage.py migrate in a Dockerfile, needs the database and fails with this error when DATABASE_URL is missing there. Run migrations when the app starts, or as a release step that has the variable, not during the build.
  • collectstatic on its own does not need a database. It runs only the staticfiles system checks[5] and copies files. If it stops with this error, your own code queried the database while Django was starting.
  • Queries at start-up are the usual reason: a query in AppConfig.ready(), or at import time, such as a form that loads its choices from a model. Django’s docs say to avoid database queries in ready(), because it runs during the startup of every management command[6], collectstatic included. Move such queries into the view, or make them lazy.

A safe default for DATABASES

The goal: real data never goes to the wrong place silently, and a missing variable says its own name.

import os
from pathlib import Path

import dj_database_url

BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = os.environ.get("DEBUG") == "1"

DATABASES = {
    "default": dj_database_url.config(
        # Local development falls back to SQLite; production must set DATABASE_URL.
        default=f"sqlite:///{BASE_DIR / 'db.sqlite3'}" if DEBUG else None,
        conn_max_age=600,
        conn_health_checks=True,
    )
}

How it behaves:

  • With DATABASE_URL set, Django uses it, in every environment.
  • Locally, with DEBUG=1 and no variable, it uses the SQLite file. For an absolute path the URL has four slashes, sqlite:////full/path/db.sqlite3, which the f-string produces[7].
  • In production, with no variable, config() logs the warning naming DATABASE_URL[8], and the first query raises this error. The build still runs, because importing settings does not open a connection[2].

A silent SQLite fallback in production is the trap to avoid: the app looks healthy, and orders or users go into a file beside the code instead of your PostgreSQL. If you would rather fail at start, read the variable strictly, dj_database_url.parse(os.environ["DATABASE_URL"])[7], which stops with KeyError: 'DATABASE_URL'; then every build step that imports settings needs the variable too.

On Livops

  • DATABASE_URL is written for you. Add a database to the project under Databases, and its address is written as a variable to every service in the environment, including services added later. For PostgreSQL the main variable is DATABASE_URL, in the form postgresql://app:<password>@postgres:5432/app, which dj-database-url reads as it is[8]. The code in cause 1 works without changes.
  • The database is inside the project. Its host is an internal name such as postgres, with no public port, so the app reaches it and your laptop does not; from your computer you connect over an SSH tunnel.
  • The build has no database. Livops runs python manage.py migrate --noinput before every start, not in the build, for a project laid out the way startproject lays it out. It runs collectstatic --noinput during the build when the project has django.contrib.staticfiles and STATIC_ROOT is set, so keep database queries out of ready() and module imports, as in cause 5.
  • Each environment has its own databases. A new staging environment gets an empty database of each type production has, and production keeps its own variables, so staging’s DATABASE_URL never points at production data.
  • Variables apply on the next deploy. A value added or changed under Variables takes effect on the next deploy; restart the service to apply it now. The traceback is on the project’s Logs page.
  • SQLite needs the kept disk. The code folder is read-only while the app runs; /app/data is kept across deploys and restarts, and its path is in DATA_DIR. A SQLite fallback on Livops should point there, sqlite:/// plus the path from DATA_DIR. That disk belongs to one app and is not backed up: once there are real users, use PostgreSQL.

A Django app costs 39 credits a month (39,000 so’m). What Livops does for Django: Frameworks. Databases and their variables: Databases. The same startup case in the docs: A variable is not set. If the database is set but refuses connections, see ECONNREFUSED / Connection refused; if it connects but the tables are missing, no such table.

Questions

What does settings.DATABASES is improperly configured mean?

Django found no ENGINE for the default database, so it loaded its dummy backend. That backend raises this error from every method that would touch the database, so the error appears on the first query, migrate or dbshell, not when settings.py is imported.

Why does dj_database_url.config() give this error?

When DATABASE_URL is not set and no default is given, or when it is set to an empty string, config() returns an empty dictionary. DATABASES = {'default': {}} then has no ENGINE, and Django falls back to the dummy backend. When the variable is missing, dj-database-url also logs a warning: No DATABASE_URL environment variable set, and so no databases setup.

Why does runserver start but every page fail?

Nothing fails while Django only loads settings. runserver's check for unapplied migrations catches this exception and skips the check, so the server starts quietly. The first view that uses the ORM, sessions or authentication then raises the error and the page answers 500.

I set a default in config() and still get the error. Why?

The variable exists but is empty, for example DATABASE_URL= in a .env file or on the server. An empty string is treated as set, so config() returns an empty dictionary instead of using the default URL. Remove the empty variable or give it a real URL.

Does collectstatic need DATABASE_URL?

Not by itself. collectstatic runs only the staticfiles system checks and does not open a database connection. If it fails with this error, something in your code queries the database while Django starts, usually in AppConfig.ready() or at import time, and Django's docs advise against that.

Is SQLite a safe default when DATABASE_URL is missing?

For local development, yes. In production a silent fallback hides the missing variable and writes real data to a file next to the code. Use the default only where DEBUG is on, or point it at a disk that is kept across deploys, and keep real data in PostgreSQL.

Where does DATABASE_URL come from on Livops?

Add a database to the project under Databases. Its address is written as a variable to every service in the environment, including services added later, and for PostgreSQL the main variable is DATABASE_URL. You do not copy it by hand.

Sources

  1. Django docs — Settings (DATABASES, ENGINE) (docs.djangoproject.com). Checked .
  2. Django source — django/db/backends/dummy/base.py (6.1) (raw.githubusercontent.com). Checked .
  3. Django source — django/db/utils.py (6.1) (raw.githubusercontent.com). Checked .
  4. Django source — django/core/management/base.py (6.1) (raw.githubusercontent.com). Checked .
  5. Django source — django/contrib/staticfiles/management/commands/collectstatic.py (6.1) (raw.githubusercontent.com). Checked .
  6. Django docs — Applications (AppConfig.ready) (docs.djangoproject.com). Checked .
  7. dj-database-url — README (raw.githubusercontent.com). Checked .
  8. dj-database-url source — dj_database_url/__init__.py (v3.1.2) (raw.githubusercontent.com). Checked .
  9. django-environ source — environ/environ.py (raw.githubusercontent.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your Django app

Got a question? — @livops_uz