python – Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

python – Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.

I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfields book Two scoops of Django.

I resolved the issue by setting

os.environ.setdefault(DJANGO_SETTINGS_MODULE, project_name.settings.local)

in manage.py and wsgi.py.

Update:

In the above solution, local is the file name (settings/local.py) inside my settings folder, which holds the settings for my local environment.

Another way to resolve this issue is to keep all your common settings inside settings/base.py and then create 3 separate settings files for your production, staging and dev environments.

Your settings folder will look like:

settings/
    __init__.py
    base.py
    local.py
    prod.py
    stage.py

and keep the following code in your settings/__init__.py

from .base import *

env_name = os.getenv(ENV_NAME, local)

if env_name == prod:
    from .prod import *
elif env_name == stage:
    from .stage import *
else:
    from .local import *

python – Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

I had the same error with python manage.py runserver.

For me, it turned out that it was because of a stale compiled binary (.pyc) file. After deleting all such files in my project, server started running again. 🙂

So if you get this error, out of nowhere, i.e without making any change seemingly-related to django-settings, this could be a good first measure.

Leave a Reply

Your email address will not be published. Required fields are marked *