[Fixed]-Django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

27👍

The .env file should be in the same directory as settings.py

👤nxoo

26👍

Solved it!!

In the .env file remove the spaces between assignment operator and var, and between value and assignment operator.
Like:

SECRET_KEY=my_secret_key_value
DEBUG=True

3👍

First, install Django-environ like this

pip install django-environ

next, import environs in your settings.py like this

import os
import environ
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
env = environ.Env()
environ.Env.read_env()


def get_env_variable(var_name):
try:
    return os.environ[var_name]
except KeyError:
    error_msg = "set the %s environment variable" % var_name
    raise ImproperlyConfigured(error_msg)


SECRET_KEY = get_env_variable('SECRET_KEY')

it is the normal Django settings file, what you did is import os, environ, ImproperlyConfigured from the exception, write the function get_env_variable and call it against the SECRET_KEY

next, create a .env file in the same directory as your settings.py file with this content

SECRET_KEY=django-insecure-b)8xiyg09+9)e4ko!o_*%5am=5(%=-%uvo5g*618619)8xcwfa

replace the secret key string with your own.
you can reference this material

3👍

  1. First Create .env file in the same directory as the settings

  2. Second, remove any space between variable and key-value (i.e
    KEY=my_key)

    import environ
    
    env = environ.Env()
    environ.Env.read_env(os.path.join(BASE_DIR, 'somepath/.env')) #<-- where ever your .env lies inside project directory
    SECRET_KEY = os.environ.get('somekeyInsidenvFile',env('somekeyInsidenvFile')) #
    

1👍

Actually there is a simple solution.

settings.py

import os
import environ

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = environ.Env()

# read th .env file
environ.Env.read_env(env_file=str(BASE_DIR) + '/.env')    

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

ALLOWED_HOSTS = ['*']
.....

.env file

SECRET_KEY=secret_key_value
DEBUG=True

Finally, don’t use spaces before and after equals in the .env file.

0👍

Having no spaces between SECRET_KEY=my_secret_key_value solved it for me!

👤Elena

0👍

clear the spaces in .env!!

In the .env file remove the spaces between assignment operator and var, and between value and assignment operator. Like:

DJANGO_SECRET_KEY="NDCNSDIWBDVIBDVUOWDVJ30F9342FE20F9JCME"
DEBUG="True"

0👍

If your SECRET_KEY starts with $ (dollar sign) you will encounter same exception as OP, which is a known bug with django-environ package.

In this case, just generate new SECRET_KEY:

from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())
👤Aron

0👍

Also had the same error. My personal issue was due to the location of the .env file.

My file structure was as follows:

BASEDIRECTORY
  Django-Project
    myapp1
    myapp2
    myInitializedProjectApp
      settings.py
      wsgi.py
      ...
  .env
  .gitignore
  Dockerfile
  ...

So my env app was at the same level as my Django-project folder

in my settings.py, after BASE_DIR is declared i included:
env.read_env('../.env')

which I guess is basically sending the folder up one from the BASE_DIR to the location of the .env it needs to read.

👤imbes

0👍

For some cases, you may want to set variables on settings based on env var, or if no env var is set use some default.

Provide a default option to avoid ImproperlyConfigured Exception,

SECRET_KEY = env('SECRET_KEY', default="asdfasdfasdfasdf")

DEBUG = env('DEBUG', default=False)

Leave a comment