Django Server KeyError - Unable to locate my environment variable

I am making a blog using Django and am trying to make it secure by using 2 settings files (prod.py and local.py which both "import *" from a base.py original settings file).

I have two environment variables which are on my local computer and have confirmed they exist: myBlog and SECRET_KEY. myBlog=prod

The error I am receiving is a KeyError:

(venv) C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog>python manage.py runserver
Traceback (most recent call last):
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 22, in <module>
    main()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute
    settings.INSTALLED_APPS
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__
    self._setup(name)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\__init__.py", line 1, in <module>
    from .base import *
  File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\myBlog\settings\base.py", line 28, in <module>
    myBlog = os.environ['myBlog']
  File "C:\Python310\lib\os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'myBlog'

This is my current init.py file:

from .base import *
import os

if os.environ['myBlog'] == 'prod':
   from .prod import *
else:
   from .local import *

This is my current base.py file:

"""
Django settings for myBlog project.

Generated by 'django-admin startproject' using Django 4.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
TEMPLATES_DIRS = os.path.join(BASE_DIR,'templates')


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

myBlog = os.environ['myBlog']

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'django.contrib.sitemaps',
]

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 = 'myBlog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_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 = 'myBlog.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

STATICFILES_DIRS = ((os.path.join(BASE_DIR, 'static')), )

STATIC_ROOT  = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

This is my current prod.py file:

from .base import *
import os

DEBUG = False
ALLOWED_HOSTS = ['mywebsite.co.uk']

This is my current local.py file:

from .base import *
import os

DEBUG = True
ALLOWED_HOSTS = ['localhost']

I am unsure of how to solve this issue. I think my environment variables are created properly (have confirmed they exist and have their expected values).

I have edited BASE_DIR to this

BASE_DIR = Path(__file__).resolve().parent.parent.parent

And both of my local.py and prod.py import * from the base.py file.

Any help would be greatly appreciated.

Back to Top