ModuleNotFoundError: No module named 'dotenv'

How do I get around ModuleNotFoundError: No module named 'dot env

Stack Overflow Link: Edit - Stack Overflow

I am doing the official django tutorial polls app on part 5 which is about testing in django. As a part of the instructions I am supposed to go into my models.py file and run the python manage.py shell command to activate a shell terminal. From there I am supposed to run a series of commands to import things for my test.

Link to material: Writing your first Django app, part 5 | Django documentation | Django

The commands I need to run are:

>>> import datetime
>>> from django.utils import timezone
>>> from polls.models import Question
>>> # create a Question instance with pub_date 30 days in the future
>>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()
True

I run the import datetime, and from django.utils import timezone and there are no issues.
Once I get to from polls.models import Question I am hit with an error message no modulenotfounderror" no module named dot env.

any advice?

settings.py

"""
Django settings for mysite 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
import os
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())


# 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 = os.environ["SECRET_KEY"]


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

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin', 
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'mysite.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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mysite_database',
    }
}


# 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 = 'US/CENTRAL'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = 'static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

commented out the non imported things.

ran the python3 command to get my bash terminal to cooperate.

ran the python manage.py shell command.

ran the import datetime, polls.modles import Question,
ModuleNotFoundError No module named ‘polls’ found.

Please show the contents of the INSTALLED_APPS setting from your settings.py file along with the contents of the apps.py file in the polls directory.

I have been working all day on this and have not made progress so if you can be of help… I would greatly appreciate it…

settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin', 
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

apps.py

from django.apps import AppConfig


class PollsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'polls'

If you run manage.py check, what is the output?

when running python manage.py check I get

ModuleNotFoundError: No module named ‘mysite’
(project_env) Andrews-MBP:mysite andrewstribling$

To confirm, you’re in the “outer” directory named “mysite”. In that directory you have directories named “mysite” and “polls”, is that correct?

You have a settings.py file in the inner “mysite” directory?

Additionally, you have a urls.py file in both of those two directories?

Yes that is correct I have an outer directory mysite and an inner directory with a folder named mysite. the polls app is in the mysite directory.
Urls.py is located in the project root folter or inner mysite folder and there is a urls.py file for the polls app as well.

I am pretty certain you said no screenshots were allowed for code, but what about folder directory assistance?
If not my github repository for this is

First, I cloned your repo and tried running manage.py check on it. Once I cleaned up a couple things, it worked.

What version of python are you using? (What is the output of python -V?)

python 3.11.3

i ran the pip install python-dotenv command just now as well as updating the time zone.

I wonder why I am having these issues. I have pushed these changes up to my repo.

it seems that from dotenv is not working. however the load_dotenv, and find_dotenv is no longer having yellow lines underneath it. Is there some way for me to get the dotenv working?

any suggestions?

I don’t know what you mean here by “not working”.

in my settings.py there are the following lines of code.

from dotenv import load_dotenv, find_dotenv

dotenv is underlined in yellow and is showing as not defined.

it is throwing an error for my program.

i set up a virtual enviornment
and ran the pip install python-dotenv and my dotenv is acting like it is not importina and my code is not working when I try to run the commands listed on part 5 of the tutorial.

when I try to run python manage.py shell and I get
KeyError: ‘SECRET_KEY’

After reviewing the python documentation I think I figured it out. Key Error means hey there is no key holding this information. I borrowed the line of code shown below because it was helping me with my secret_key setup. But the thing is I don’t have access to that dictionary data. Either I need to revisit the instructions or find another way to set up my secret_key.

SECRET_KEY=os.environ["SECRET_KEY"]

That is your IDE doing that. Whether or not it’s significant is a completely separate issue.

See the docs for os.environ

In your own words, what do you think that line of code does?

Before checking the documentation that was a line of code someone gave me as part of a setup for a way to hide my secret key.
Per the documentation,
A mapping object where keys and values are strings that represent the process environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C.

In my own words it seems like this is an object of some sort that influences the environment variables in my project.

per the documentation: This mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified.

I think this reinforces what I suspect.

Thinking this through my question are,

what are enviornment variables? → I will be looking that up in the python documentation

“We can use Python os module “environ” property to get the dictionary of all the environment variables. When the os module is loaded by Python interpreter, the environ value is set. Any further changes in the environment variables through external programs will not get reflected in the already running Python program.”

Why are these lines of code necessary? → I need to check the stack overflow article that talked about setting this up.
Link to that is here: Where to store secret keys DJANGO - Stack Overflow

It can - more commonly, it’s used to give your program access environment variables. (Changing the environment in Django doesn’t do you a lot of good. The value in Django is allowing it to read those environment variables.)

That’s a good place to start, but you should be aware that environment variables exist for every program that runs.

Please, do yourself a favor and do not rely up SO as a primary source of information. Save yourself some headaches and always double-check anything you see on there from a primary source.

Assuming you’re referring to:

It’s getting the environment variable named SECRET_KEY, and assigning it to the settings variable named SECRET_KEY.

Until you are comfortable with environment variables and how they’re used, you can save yourself some problems by just assiging a secret key in your settings.

so the solution may be to remove this code and use git ignore to stop my secret_keys from being uploaded to github

I need to check the documentation about the best way to save my secret keys. leaving it in settings.py leaves the secret key getting uploaded to github. I have been told to use a txt file and gitignore but if there is a more conventional way I am open to it.

That’s one option, there are others.

Since we’re talking about a tutorial here, you could simply ignore the security issues with your SECRET_KEY being in github. Yes, it’s not something you want to do with a real system - but while you’re learing your way through things, this is one of those issues that can safely be ignored.

1 Like

it migth be a bit late but did you try this ?

add these line to manay.py inside of main function

"""Run administrative tasks."""
dotenv.read_dotenv()

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'path.settings')

also install django-dotenv and also don’t forget to uninstall python-dotenv

more info here GitHub - jpadilla/django-dotenv: Loads environment variables from .env