EnvError Environment variable debug not set

Hello Django Forum:

I am working on Django for beginners and in Django for beginners I am told to create an .env file and have it exisit in the same root directory next to the existing .gitignore file. It teaches that we should never deploy a site into production with DEBUG turned on as it provides a treasure map for hackers to destroy or alter my website. Instead we want debug to be true for local development and false for production. In the instructions it says go into my .env file and set DEBUG=True without spaces and than for my django_project/settings.py file have the DEBUG = env.bool(“DEBUG”)

I do this and I get the following error message

ERROR MESSAGE:
(.venv) andrewstribling@Andrews-MBP blog % python manage.py runserver
Traceback (most recent call last):
File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 22, in
main()
File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 18, in main
execute_from_command_line(sys.argv)
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 442, in execute_from_command_line
utility.execute()
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 382, in execute
settings.INSTALLED_APPS
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 102, in getattr
self._setup(name)
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 89, in _setup
self._wrapped = Settings(settings_module)
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 217, in init
mod = importlib.import_module(self.SETTINGS_MODULE)
File “/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/init.py”, line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 1030, in _gcd_import
File “”, line 1007, in _find_and_load
File “”, line 986, in _find_and_load_unlocked
File “”, line 680, in _load_unlocked
File “”, line 850, in exec_module
File “”, line 228, in _call_with_frames_removed
File “/Users/andrewstribling/Desktop/code/blog/django_project/settings.py”, line 30, in
DEBUG = env.bool(“DEBUG”)
File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/environs/init.py”, line 116, in method
raise EnvError(‘Environment variable “{}” not set’.format(proxied_key or parsed_key))
environs.EnvError: Environment variable “DEBUG” not set
(.venv) andrewstribling@Andrews-MBP blog %

commentary about error message

I observe this part:
File “/Users/andrewstribling/Desktop/code/blog/django_project/settings.py”, line 30, in
DEBUG = env.bool(“DEBUG”)

this leads me to believe it is one of two things, my file folder is wrong and it is not reading it, or I have set up my DEBUG incorrectly. I have tried including spaces as well. And I have looked on stack overflow. here is how it currently is in my visual studio code. my repository link is: GitHub - strikeouts27/django_for_beginners_blog: Django For Beginners Blog

I have tried eliminating the spaces, and I have tried copying and pasting directly from the source material but the problem remains. Is there any other way I can troubleshoot this?

settings.py

"""
Django settings for django_project project.

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

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

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

from pathlib import Path
from environs import Env

env = Env() 
env.read_env 

# 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/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-n7o2s^7n@a*xi-5q3jc*5^^s1^yj=o8_5!d3#31*o)fh(mz+=r"

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "whitenoise.runserver_nostatic",
    "django.contrib.staticfiles",
    "blog", 
    'accounts', 
]

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

ROOT_URLCONF = "django_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "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 = "django_project.wsgi.application"


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

DATABASES = {
"default": env.dj_db_url("DATABASE_URL", default="sqlite:///db.sqlite3"),
}


# Password validation
# https://docs.djangoproject.com/en/4.2/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.2/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.2/howto/static-files/

# this is the url location of static files in our project. 
STATIC_URL = "static/"

# STATICFILES_DIRS defines addiitonal locations the built-in staticfiles app will traverse looking for static files
# beyond an app/static folder. We need to set it to have a project-level static folder instead, and it is also necessary for local static file viewing.
STATICFILES_DIRS = [BASE_DIR / "static"] 

# STATIC_ROOT 
# Static root- the directory location of all static files complied when collectstatic is run.
# We will set it to the standard default of staticfiles meaning there will be a project-level folder
# with that naming containing all the static files ready for production. 
STATIC_ROOT = BASE_DIR/ "staticfiles"

# STATICFILES_STORAGE 
# The file storage engine used by collect static. The default is STATICFILES_STORAGE and it is 
# implicity set right now so we explicitly set it on the next line of code. 

# On this next line of code we updated the default STATICFILES_STORAGE engine to use WhiteNoise when running the collect static management command.
# When we run the collect static command we can have all of the collected static files be regenerated in the same static files folder. 
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Login View requires that you set a redirect. This is established on the following line of code.
LOGIN_REDIRECT_URL = "home" 
LOGOUT_REDIRECT_URL = "home"

.env

'''Our goal is for DEBUG to be True for local development but set to False in production. The two-
step process for adding any environment variable is first adding it to the .env file and then to
django_project/settings.py. Within the .env file, create a new environment variable called
DEBUG; we will set its value to True. It is important not to have any spaces here.'''

DEBUG=True

You didn’t call read_env method of Env class, so I guess variables from your .env file weren’t load. You have to add parenthesis so it will look like this env.read_env() to make function call and actually read variables.

Also it is sometimes good idea to provide default value for secrets, DEBUG = env.bool("DEBUG", True) Then you don’t need to specify debug in .env file on local but have to add it on production or in reverse.