Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Greenfield's 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 *

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.


Remove .pyc files

Ubuntu terminal command for deleting .pyc : find . -name "*.pyc" -exec rm -rf {} \;

I have got same error when I did python manage.py runserver. It was because .pyc file. I deleted .pyc file from project directory then it was working.


I hadn't specified the settings file:

python manage.py runserver --settings=my_project.settings.develop