django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
Asked Answered
H

10

17

This project was working fine until I used environ to make SECRET_KEY and DEBUG as environment variable using environ. After I am getting this error:-

The output is:

(env) E:\ecommercedj>python manage.py runserver
Traceback (most recent call last):
  File "E:\ecommercedj\env\lib\site-packages\environ\environ.py", line 273, in get_value
    value = self.ENVIRON[var]
  File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute
    super().execute(*args, **options)
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle
    if not settings.DEBUG and not settings.ALLOWED_HOSTS:
  File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__
    self._setup(name)
  File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 63, in _setup
    self._wrapped = Settings(settings_module)
  File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 142, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "E:\ecommercedj\ecom\settings.py", line 11, in <module>
    SECRET_KEY = env('SECRET_KEY')
  File "E:\ecommercedj\env\lib\site-packages\environ\environ.py", line 123, in __call__
    return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
  File "E:\ecommercedj\env\lib\site-packages\environ\environ.py", line 277, in get_value
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

(env) E:\ecommercedj>

settings.py

import os
import environ

env = environ.Env()

# read th .env file
environ.Env.read_env()

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

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

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

.env file

SECRET_KEY value is unquoted

SECRET_KEY = my_secret_key_value
DEBUG = True

The project was running fine before adding environ. Am I getting the error because of eviron? How should I remove this error?

Humanize answered 28/7, 2020 at 15:7 Comment(4)
put SECRET_KEY = "my_secret_key_value" put quotes in .env fileDwaindwaine
What lib are you using to handle environment variables?Quinonez
I have tried putting "my_secret_key_value" in quotes. It still doesn't work. I am using ENVIRON for handling environment variables.Humanize
if you are using docker container you must do additional settingsMcwhirter
B
32

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

Burchette answered 25/2, 2021 at 12:34 Comment(2)
This problem has already been resolved and was not related to the location of the file.Tosspot
After moving the file to same level as settings.py the problem got removedFastness
H
27

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
Humanize answered 29/7, 2020 at 2:56 Comment(0)
W
4
  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')) #
    
Wandis answered 4/9, 2021 at 8:46 Comment(0)
A
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

Allotropy answered 2/6, 2021 at 15:21 Comment(0)
W
3

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.

Wideawake answered 1/1, 2022 at 11:36 Comment(0)
L
2

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"
Lebkuchen answered 8/8, 2021 at 11:47 Comment(0)
L
1

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

Living answered 8/2, 2021 at 15:26 Comment(0)
R
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())
Raguelragweed answered 20/8, 2021 at 12:14 Comment(0)
D
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.

Diabetic answered 18/4, 2022 at 20:27 Comment(0)
H
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)
Honeywell answered 4/9, 2023 at 1:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.