'trying to make django load environment vars from a .env.local file using django-environ from within a venv

I keep getting this traceback

(pythonApp) D:\task_trackv2>python manage.py makemigrations
D:\task_trackv2\apps_config\settings.py
D:\pythonApp\lib\site-packages\environ\environ.py:637: UserWarning: Error reading .env.local - if you're not configuring your environment separately, check this.
  warnings.warn(
D:\task_trackv2\apps_config\settings.py
D:\task_trackv2\apps_config\settings.py
Traceback (most recent call last):
  File "D:\pythonApp\lib\site-packages\environ\environ.py", line 273, in get_value
    value = self.ENVIRON[var]
  File "c:\users\belkin\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 "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 366, in execute
    self.check()
  File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 392, in check
    all_issues = self._run_checks(
  File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:\pythonApp\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:\pythonApp\lib\site-packages\django\core\checks\translation.py", line 60, in check_language_settings_consistent
    get_supported_language_variant(settings.LANGUAGE_CODE)
  File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__
    self._setup(name)
  File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 63, in _setup
    self._wrapped = Settings(settings_module)
  File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 142, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "c:\users\belkin\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 "D:\task_trackv2\apps_config\settings.py", line 38, in <module>
    SECRET_KEY = env('SECRET_KEY')
  File "D:\pythonApp\lib\site-packages\environ\environ.py", line 123, in __call__
    return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
  File "D:\pythonApp\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

I don't really know what's the issue here, maybe there's something I'm missing due to the fact that I'm working in a venv, but I can't be certain. On the django-environ docs page it says that this error would occur if SECRET_KEY isn't set in os.environ, but setting it through the python console gave no effect

this is my settings.py:

import environ
from typing import List

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)


environ.Env.read_env(env_file='.env.local')

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')

ALLOWED_HOSTS: List[str] = ['*']


AUTH_USER_MODEL = 'user.User'


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'apps.base',
    'apps.user',
    'apps.team',
    'apps.notes',
    'apps.invite'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'apps_config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'apps_config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

and this is my .env.local file (same location as settings.py):

DEBUG=True
SECRET_KEY='8x0=1jo1b-db5tz%f=q%)j8%4y(^_b0g9w#0+ugu(@i-u2d!1'
DB_NAME='task_trackv2'
DB_USER='task_track'
DB_PASSWORD='1234'
DB_HOST='localhost'
DB_PORT='5432'


Solution 1:[1]

Below instruction was how I solve this problem in my project.

In the .env file, the secret key should be SECRET_KEY=generate_secret_key.

And in the settings.py the lineSECRET_KEY = env('SECRET_KEY') should be SECRET_KEY = env.str('SECRET_KEY', 'sample_unsafe_secret').

Solution 2:[2]

In the settings.py file, the line SECRET_KEY = env('SECRET_KEY') should be SECRET_KEY = env('SECRET_KEY', 'sample_secret')

If you do not specify the default value for your environment variable, you get the ImproperlyConfigured error.

Solution 3:[3]

You must not use quotations in .env file. How it must be:

DEBUG=True
SECRET_KEY=8x0=1jo1b-db5tz%f=q%)j8%4y(^_b0g9w#0+ugu(@i-u2d!1
DB_NAME=task_trackv2
DB_USER=task_track
DB_PASSWORD=1234
DB_HOST=localhost
DB_PORT=5432

Defining default value is an option but that is for the time that you don't or you can't use the .env file. So as soon as you want to use environ file, you need to configure the file well to receive all the values.

Anyway defining default value is like this:

SECRET_KEY = env("SECRET_KEY", default="unsafe-secret-key")

Solution 4:[4]

I think the problem is in your file path. You can set your path on any of these below methods.

env.read_env(BASE_DIR('.env'))

env.read_env(os.path.join(BASE_DIR, '.env'))

env.read_env(pathlib.Path(str(BASE_DIR)).joinpath('.env'))

env.read_env(pathlib.Path(str(BASE_DIR)) / '.env')

you can refer to more on django-environ

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kmz
Solution 2 Noopur Phalak
Solution 3 Berkay
Solution 4 Xavier Guihot