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 file and run the python 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( + datetime.timedelta(days=30))
>>> # was it published recently?
>>> future_question.was_published_recently()

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?

Django settings for mysite project.

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

For more information on this file, see

For the full list of settings and their values, see

from pathlib import Path
import os
from dotenv import 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

# 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


# Application definition



ROOT_URLCONF = 'mysite.urls'

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database

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

# Password validation

        '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



USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_URL = 'static/'

# Default primary key field type

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 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 file along with the contents of the 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…


from django.apps import AppConfig

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

If you run check, what is the output?

when running python 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 file in the inner “mysite” directory?

Additionally, you have a 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. is located in the project root folter or inner mysite folder and there is a 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 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 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 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.


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 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 inside of main function

"""Run administrative tasks."""

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