ImproperlyConfigured: The SECRET_KEY setting must not be empty (Django): how to fix it
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty means Django read SECRET_KEY and found nothing in it. After a deploy that is almost always settings.py reading the key from an environment variable that is not set on the server, a .env file that was never deployed, or a different settings module than you think. Set SECRET_KEY as a variable on the server, generate a new random one for production, and never commit it.
By Livops team, the people who build and run LivopsUpdated
The app starts, or a management command runs, and stops with this at the end of the traceback:
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Django found SECRET_KEY empty. On a server that almost always means the value lives somewhere the server cannot see. This page explains when Django raises it, lists the causes after a deploy, most common first, and shows how to generate a key and keep it out of your repository. For the whole production setup of a Django app, see Django hosting.
What the error means
SECRET_KEY is the key Django uses for cryptographic signing; it should be a unique, unpredictable value, and Django refuses to start if it is not set[1]. Its default is an empty string[1], so a settings module that never sets it gets this error too.
The check is in Django’s settings object: the first time code reads settings.SECRET_KEY, Django raises this exception if the value is empty, and None counts as empty[4]. Because the check runs on that first read, not when settings.py is imported, the error can show up at startup, inside a management command, or only when the first request needs the key. Sessions, password reset tokens and cookie-based messages all use it[1].
Causes, most common first
1. The environment variable is not set on the server
The usual settings.py reads the key from the environment:
import os
SECRET_KEY = os.environ.get("SECRET_KEY")
os.environ is a mapping of the process’s environment, and os.getenv and .get return their default, None, when the variable does not exist[10]. On your machine the variable is set; on the server it is not, SECRET_KEY becomes None, and Django raises this error. An empty default, os.environ.get("SECRET_KEY", ""), ends the same way.
Fix: set SECRET_KEY in the server’s environment, under exactly that name, and restart the app. To make a missing variable fail with its own name, read it the way Django’s deployment checklist does[2]:
import os
SECRET_KEY = os.environ["SECRET_KEY"]
Now a missing variable stops the app with KeyError: 'SECRET_KEY', which says what to set.
The libraries that read settings from the environment do the same by default:
- python-decouple.
config("SECRET_KEY")raisesUndefinedValueErrorwhen the value is missing and no default is given[11]. - django-environ.
env("SECRET_KEY")raises Django’sImproperlyConfiguredwithSet the SECRET_KEY environment variable[12][13].
So if you use one of them and still see must not be empty, the variable exists but is empty, or the call has a default="". Remove the default and set the variable.
2. The .env file was never deployed
python-decouple looks for a .env or settings.ini file up the path of your settings module[11], and django-environ reads one with environ.Env.read_env()[12]. That file is listed in .gitignore, as it should be: django-environ’s docs say the .env file should be specific to the environment and not checked into version control[12]. So the repository the server gets has no .env, and the key you set in it locally never arrives.
Fix: do not commit .env to make the error go away. Set the same names as environment variables on the server. Both libraries let a real environment variable win over the file: decouple searches environment variables first[11], and read_env does not overwrite variables that already exist[13]. The same settings code then works with the file on your machine and with variables on the server. To show which names a deploy needs, commit a .env.example with the names and dummy values, as django-environ suggests with its .env.dist[12].
3. Django loads a different settings module than you think
Django reads the settings module named in the DJANGO_SETTINGS_MODULE environment variable, in Python path syntax such as mysite.settings[3]. The manage.py and wsgi.py that startproject creates set it with os.environ.setdefault[8][9], which only fills it in when it is not already set. If the server sets DJANGO_SETTINGS_MODULE to another module, that module wins.
This bites projects that split settings into base.py, dev.py and production.py: the key is set in dev.py only, or the production module imports base and never sets it. Since the default is an empty string[1], a module that does not set SECRET_KEY produces this error. Check which module is actually loaded, with the server’s environment:
echo "$DJANGO_SETTINGS_MODULE"
python manage.py shell -c "from django.conf import settings; print(settings.SETTINGS_MODULE)"
Then make sure that module sets SECRET_KEY. For a one-off command you can pass the module with --settings[3].
4. The variable is set for the build, not for the running app
A CI job or a build step can have the variable while the app that runs afterwards does not. In Docker, ARG values are not persisted into the built image the way ENV values are[14], so a key passed as --build-arg is gone when the container starts. Do not fix that by baking the key into the image: Docker’s docs recommend against build arguments for secrets such as API tokens[14]. Give the key to the running container as an environment variable from the platform or orchestrator that starts it.
The opposite happens too: a build step that imports your settings, such as collectstatic, runs where only the running app has the variable. With os.environ["SECRET_KEY"] that step stops with KeyError: 'SECRET_KEY' in the build output. With .get() it may pass, since Django checks the key only when something reads it[4], and leave the error for later. Make the variable available to that step as well.
Generate a key and keep it secret
Generate a production key with the same function startproject uses:
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
get_random_secret_key() returns a random 50-character string[5]. startproject puts it in the new project’s settings with the prefix django-insecure-[6], which marks a key that was written into a file and should not reach production. manage.py check --deploy warns (security.W009) about a key shorter than 50 characters, with fewer than 5 unique characters, or with that prefix[7]; Django’s deployment checklist says to run it against your production settings[2].
Rules for the key itself:
- Keep it secret. Running Django with a known
SECRET_KEYdefeats many of its security protections and can lead to privilege escalation and remote code execution[1]. - Do not commit it, and do not reuse it. The deployment checklist says the production key should not be used anywhere else and should not be committed to source control[2].
- Keep it stable. When the key changes, sessions, password reset tokens, cookie-based messages and other signed data made with the old key become invalid; user passwords are not affected[1]. So generate it once and store it. Do not call
get_random_secret_key()insettings.py: every restart would log everybody out. - Rotate with fallbacks. To replace a key, set the new one as
SECRET_KEYand move the old one to the start ofSECRET_KEY_FALLBACKS; remove it from there when old sessions and tokens may expire[1].
On Livops
- The key goes in Variables. Open Settings → Variables, add
SECRET_KEYwith the generated value, and mark it as a secret: its value is never shown again after saving, not in the cabinet, not in the API, and the assistant sees only its name. New values take effect on the next deploy; restart the service to apply one now. .envdoes not reach the server. An.envfile stays out of the repository, so the values go in Variables instead. Livops’s docs list a missing variable such asSECRET_KEYas the most common reason an app does not start.- Where you see it. When the app stops on this error, the deploy fails as
start_failedand the reason is on the Logs page. A web app’s previous version keeps running while you fix it. - The build loads your settings too. For a Django project with
STATIC_ROOTset, Livops runscollectstaticduring the build. So a build log that stops wheresettings.pyreadsSECRET_KEYis cause 4 above: your settings are loaded during the build as well as at start. - A key per environment. A new environment such as
staginggets copies of production’s variables, and promoting a release keeps production’s own variables. Givestagingits ownSECRET_KEY, so the production key is used nowhere else.
What Livops does for Django, including migrate and ALLOWED_HOSTS: Frameworks. The same startup case in the docs: A variable is not set. If the next error after this one is about the host name, see DisallowedHost.
Questions
Why does it work on my computer and fail on the server?
On your computer the key comes from somewhere the server does not have: a .env file that git ignores, a variable exported in your shell, or a settings file with the key written into it. The server has the code from the repository and only the environment variables you set there.
How do I generate a new SECRET_KEY?
Run python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())". The function returns a random 50-character string, the same generator startproject uses. Generate it once and store it as a variable on the server.
Can I reuse the key from my development settings?
No. Keys made by startproject start with django-insecure-, and check --deploy flags them. Django's deployment checklist also says the production key should not be used anywhere else. Generate a separate key for production.
Can settings.py generate a random key on every start?
It starts, but it breaks things. Sessions, password reset links and signed data made with the old key stop being valid whenever the key changes, so every restart logs everybody out, and two worker processes would each have a different key. Keep one stable key in a variable.
What happens if I change the key?
Sessions, password reset tokens, cookie-based messages and anything signed with the old key become invalid. User passwords are not affected. To rotate without logging everyone out at once, put the old key in SECRET_KEY_FALLBACKS for a while.
I committed my SECRET_KEY to git. What now?
Treat it as known. Generate a new key, set it as a variable on the server, and read it from the environment in settings.py. Move the old one to SECRET_KEY_FALLBACKS only for as long as you need old sessions to keep working, then remove it.
Where do I put SECRET_KEY on Livops?
In Settings, Variables: add SECRET_KEY with the key as the value and mark it as a secret, so its value is never shown again after saving. Deploy again or restart the service to apply it.
Sources
- Django docs — Settings (SECRET_KEY) (docs.djangoproject.com). Checked .
- Django docs — Deployment checklist (docs.djangoproject.com). Checked .
- Django docs — Django settings (docs.djangoproject.com). Checked .
- Django source — django/conf/__init__.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/core/management/utils.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/core/management/commands/startproject.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/core/checks/security/base.py (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/conf/project_template/manage.py-tpl (6.1) (raw.githubusercontent.com). Checked .
- Django source — django/conf/project_template/project_name/wsgi.py-tpl (6.1) (raw.githubusercontent.com). Checked .
- Python docs — os (os.environ, os.getenv) (docs.python.org). Checked .
- python-decouple — README (raw.githubusercontent.com). Checked .
- django-environ docs — Quick Start (django-environ.readthedocs.io). Checked .
- django-environ source — environ/environ.py (raw.githubusercontent.com). Checked .
- Docker docs — Dockerfile reference (docs.docker.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Django appRelated
- Django hosting in 2026: how to deploy a Django app, and whereFor most Django apps, a platform that deploys from Git is the right pick: Render and DigitalOcean App Platform are the simplest fixed monthly prices, Fly.io is the cheapest in dollars, Railway bills by usage, and a VPS is for when you want root. Livops fits Django apps whose users are in Uzbekistan, at 39 credits a month. Below: prices and free tiers side by side, a Django deployment checklist, and how to host a Django project on Livops.
- DisallowedHost: Invalid HTTP_HOST header — Django's 400 Bad RequestDjango received a request for a host name that is not in ALLOWED_HOSTS, so it answered 400 Bad Request. Add the domain the site is served on to ALLOWED_HOSTS, without https:// and without a port, or read the list from an environment variable, and redeploy.
- Django OperationalError: no such table (and relation does not exist): how to fix itdjango.db.utils.OperationalError: no such table on SQLite, or ProgrammingError: relation does not exist on PostgreSQL, means the table your model needs is not in the database the app is connected to. After a deploy that is usually migrate not run on the production database, migration files never committed, an app missing from INSTALLED_APPS, or a new empty SQLite file. Commit the migrations, run python manage.py migrate against the right database, and check with showmigrations.
- Gunicorn "Worker failed to boot": what it means and how to fix itGunicorn's worker could not load your application, so the master process shut down. The cause is the Python traceback printed just above the message: most often a missing package or variable, or a wrong module:variable path in the gunicorn command. Fix what the traceback names and the workers boot.
- Forbidden (403) CSRF verification failed. Request aborted. — Django after deployForbidden (403) CSRF verification failed. Request aborted. means Django's CSRF middleware refused a POST. Right after moving behind HTTPS and a proxy, the usual reason is Origin checking failed: add the site's origin with its scheme, such as https://example.com, to CSRF_TRUSTED_ORIGINS. For CSRF cookie not set or CSRF token missing, put the csrf_token tag in the form or send the X-CSRFToken header.
- ModuleNotFoundError: No module named — after a deployPython searched sys.path and could not find the module you import. After a deploy that almost always means the package is not in requirements.txt, is listed under a different name than the one you import, or the start command runs a Python that the packages were not installed into.
- ImproperlyConfigured: settings.DATABASES is improperly configured (Django): how to fix itdjango.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.