[Django]-Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

131👍

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.

94👍

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 *
👤Jinesh

23👍

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.

18👍

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.

16👍

I hadn’t specified the settings file:

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

8👍

It starts working because on the base.py you have all information needed in a basic settings file. You need the line:

SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*'

So it works and when you do from base import *, it imports SECRET_KEY into your development.py.

You should always import basic settings before doing any custom settings.


EDIT:
Also, when django imports development from your package, it initializes all variables inside base since you defined from base import * inside __init__.py

8👍

I had the same problem with Celery. My setting.py before:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

after:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', <YOUR developing key>)

If the environment variables are not defined then: SECRET_KEY = YOUR developing key

7👍

I think that it is the Environment error,you should try setting : DJANGO_SETTINGS_MODULE='correctly_settings'

6👍

for development just update settings.py, and should work

SECRET_KEY = '*'
👤0xFK

5👍

For anyone using PyCharm: the green “Run selected configuration” button would produce this error, yet running the following works:

py manage.py runserver 127.0.0.1:8000 --settings=app_name.settings.development

To fix this you need to edit the configuration’s environment variables. To do this click the “Select run/debug configuration” drop-down menu to the left of the green run button and then click on “edit configuration”. Under the “environment” tab change the environment variable DJANGO_SETTINGS_MODULE to app_name.settings.development.

4👍

In the init.py of the settings directory write the correct import, like:

from Project.settings.base import *

No need to change wsgi.py or manage.py

3👍

I solved this problem occurring on OS X with Django both 1.5 and 1.6 by deactivating all active sessions to virtualenv and starting it again.

2👍

To throw another potential solution into the mix, I had a settings folder as well as a settings.py in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)

Python was getting confused about whether I wanted to import project/settings.py or project/settings/__init__.py. I removed the settings dir and everything now works fine.

1👍

I just wanted to add that I got this error when my database name was spelled wrong in my settings.py file so the DB couldn’t be created.

👤Lexo

1👍

I solved this problem on 1.8.4 by fixing the TEMPLATES settings which had a typo (removing TEMPLATES[‘debug’] solved it)

Go over the settings that you have changed recently, make sure all keys are by-the-book.

1👍

My Mac OS didn’t like that it didn’t find the env variable set in the settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

but after adding the env var to my local Mac OS dev environment, the error disappeared:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

In my case, I also needed to add the --settings param:

python3 manage.py check --deploy --settings myappname.settings.production

where production.py is a file containing production specific settings inside a settings folder.

👤Samer

1👍

The issue for me was calling get_text_noop in the LANGUAGES iterable.

Changing

LANGUAGES = (
    ('en-gb', get_text_noop('British English')),
    ('fr', get_text_noop('French')),
)

to

from django.utils.translation import gettext_lazy as _

LANGUAGES = (
    ('en-gb', _('British English')),
    ('fr', _('French')),
)

in the base settings file resolved the ImproperlyConfigured: The SECRET_KEY setting must not be empty exception.

👤Sepia

1👍

The reason why there are so many different answers is because the exception probably doesn’t have anything to do with the SECRET_KEY.
It is probably an earlier exception that is being swallowed.
Turn on debugging using DEBUG=True to see the real exception.

1👍

In my case, it was because I was trying to setup django-environ and I missed an important step:

Note: In the instructions below .env.example and .env should be saved in the same folder as settings.py

I incorrectly assumed that .env belonged in the root of my project. Moving it to the same folder as settings.py fixed the problem.

This error message in the Python console was the clue that set me on the right path:

Warning: /Users/allen/PycharmProjects/myapp/myapp/.env doesn't exist - if you're not configuring your environment separately, create one.

0👍

I solved this problem by removing the spaces around equal signs (=) in my .env file.

👤aiven

0👍

In my case the problem was – I had my app_folder and settings.py in it. Then I decided to make Settings folder inside app_folder – and that made a collision with settings.py. Just renamed that Settings folder – and everything worked.

0👍

I solved the above problem by commenting the line in my settings.py

SECRET_KEY=os.environ.get('SECRET_KEY')

SECRET_KEY declared in my ~/.bashrc file(for linux Ubuntu users)

For development purpose on my localmachine I did not use evironmnet variable

SECRET_KEY = '(i9b4aes#h1)m3h_8jh^duxrdh$4pu8-q5vkba2yf$ptd1lev_'

above line didn’t give the error

0👍

In my case, while setting up a Github action I just forgot to add the env variables to the yml file:

jobs:
  build:
    env:
     VAR1: 1
     VAR2: 5

0👍

In my case, after a long search I found that PyCharm in your Django settings (Settings > Languages & Frameworks > Django) had the configuration file field undefined. You should make this field point to your project’s settings file. Then, you must open the Run / Debug settings and remove the environment variable DJANGO_SETTINGS_MODULE = existing path.

This happens because the Django plugin in PyCharm forces the configuration of the framework. So there is no point in configuring any os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, ‘myapp.settings’)

0👍

Import base.py in __init__.py alone. make sure you won’t repeat the same configuration again!.

set environment variable
SET DJANGO_DEVELOPMENT =dev

settings/
  __init__.py
  base.py
  local.py
  production.py

In __init__.py

from .base import *
if os.environ.get('DJANGO_DEVELOPMENT')=='prod':
   from .production import *
else:
   from .local import *

In base.py configured the global configurations. except for Database. like

SECRET_KEY, ALLOWED_HOSTS,INSTALLED_APPS,MIDDLEWARE .. etc....

In local.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'database',
    'USER': 'postgres',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '5432',
}
}

0👍

I came here looking for answer as I was facing the same issues, none of the answers here worked for me. Then after searching in other websites i stumbled upon this simple fix. It worked for me

wsgi.py

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings')

to

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yourProject.settings.dev')

0👍

Let me share m interesting solution!

I put the
SECRET_KEY = "***&^%$#" in settings packages init.py file and the error disappeared! it’s actually a loading problem!

Hope this quick workaround is useful for some of you!

👤auvipy

0👍

try import django then run django.setup() after the secret_key definition. like so:

SECRET_KEY = 'it5bs))q6toz-1gwf(+j+f9@rd8%_-0nx)p-2!egr*y1o51=45XXCV'
django.setup()

0👍

For anyone using Wing IDE: set the DJANGO_SETTINGS_MODULE in your project properties to DJANGO_SETTINGS_MODULE=${DJANGO_SITENAME}.config.settings.development

You will find the settings under: Project –> Project Properties and set the value in the field Environment

0👍

(I am using Pycharm, I also tried every solution in here and found out that the solutions works on some codes and some doesn’t so I just did this solution)

The easiest Resolution that I did is I deleted the LIB where the installed sitepackages are, opened python interpreter in the settings and then it gave me an option where the program(Pycharm) installed the pip/sitepackges and I reinstalled the rest of the packges for example rest_framewrok etc. in the virtual environment of the project using cmd(or any command prompt tool) and it fixed my problem.

👤Shad0w

0👍

I used a web service to generate a random key: https://djecrety.ir/

It had multiple dollar signs in it and ruined my manage.py runs. Pycharm’s Run Configuration worked fine with it.

0👍

In my case nothing worked because I source-ed .env file. I was able to see the values of the variable with echo $SECRET_KEY but python process didn’t see it. This happens because it isn’t exported, so I had to export all values with the following command:

eval $(egrep -v '^(#|$)' .env | sed 's|^|export |')

0👍

Since Django 3.0 , the AdminEmailHandler logging handler can raise this, since it tries to read the default reporter_class from settings – which creates a kind of circular dependency issue.

A solution is to set the reporter_class in the config of the handler:

"mail_admins": {
    "level": "ERROR",
    "class": "django.utils.log.AdminEmailHandler",
    "reporter_class": "django.views.debug.ExceptionReporter",                                              
},

Source: https://code.djangoproject.com/ticket/32016#comment:9

👤mfit

Leave a comment