ImportError/ModuleNotFoundError

Hi, I’m trying to work through the tutorial. I’m currently on the testing section and when I go to run the test:
python manage.py test polls

I get the following error:

System check identified no issues (0 silenced).
E

ERROR: mysite.polls (unittest.loader._FailedTest)

ImportError: Failed to import test module: mysite.polls
Traceback (most recent call last):
File “/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py”, line 470, in _find_test_path
package = self._get_module_from_name(name)
File “/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py”, line 377, in _get_module_from_name
import(name)
ModuleNotFoundError: No module named ‘mysite.polls’


Ran 1 test in 0.000s

FAILED (errors=1)

I’m not really sure what’s going on I’ve been trying to figure it out and research it for the past few hours.

Thanks for the help

Are you able to show us your directory structure? Use dir in the command prompt (or equivalent) in Windows, or ls (Linux and Mac) so we can see what you have.

-Jorge

I’m working with a Mac
Tree

I have the feeling that having the top level folder (named mysite) and the project folder (also named mysite but the path is mysite/mysite) may be confusing the test runner. I would try renaming the top level mysite to something else (maybe mysite_root). Then try again.

-Jorge

I was thinking the same thing. So, I changed the outer mysite and got a similar error which is posted below.

I was under the impress that this mysite (shell)/mysite (inner) was just normal Django convention?

System check identified no issues (0 silenced).
E

ERROR: mysite_root.polls.tests (unittest.loader._FailedTest)

ImportError: Failed to import test module: mysite_root.polls.tests
Traceback (most recent call last):
File “/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py”, line 436, in _find_test_path
module = self._get_module_from_name(name)
File “/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py”, line 377, in _get_module_from_name
import(name)
File “/Users/dijon.henderson/PycharmProjects/learn_django/mysite_root/polls/tests.py”, line 6, in
from .models import Question
File “/Users/dijon.henderson/PycharmProjects/learn_django/mysite_root/polls/models.py”, line 16, in
class Question(models.Model):
File “/Users/dijon.henderson/PycharmProjects/learn_django/venv/lib/python3.8/site-packages/django/db/models/base.py”, line 112, in new
raise RuntimeError(
RuntimeError: Model class mysite_root.polls.models.Question doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.


Ran 1 test in 0.013s

FAILED (errors=1)

Can you post your settings.py please?

-J

import os

Build paths inside the project like this: os.path.join(BASE_DIR, …)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))

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

DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3’,
‘NAME’: os.path.join(BASE_DIR, ‘db.sqlite3’),
}
}

Password validation

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

LANGUAGE_CODE = ‘en-us’

TIME_ZONE = ‘America/New_York’

USE_I18N = True

USE_L10N = True

USE_TZ = True

Static files (CSS, JavaScript, Images)

STATIC_URL = ‘/static/’

Sorry for the delay. In trying to troubleshoot this, I found I had a broken Python 3.8 installation. Now fixed. Yay!

I tried this steps exactly as in the tutorial (I have done the tutorial a couple of times in the past, and this time in the interest of time I copied and pasted. I don’t recommend it while one is learning). I got the test to run using the top level folder of “mysite”. So, my original premise was incorrect.

Can you please post your tests.py, please?

-J

Lol. Crazy, well thanks so far. See below for my tests.py

import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Question

class QuestionModelTests(TestCase):

def test_was_published_recently_with_future_question(self):
    """
    was_published_recently() returns False for questions whose pub_date
    is in the future.
    """
    time = timezone.now() + datetime.timedelta(days=30)
    future_question = Question(pub_date=time)
    self.assertIs(future_question.was_published_recently(), False)

This certainly has been a bit of a journey there and back again (minus the ring and Mordor). May I ask if running the development server works without errors (python manage.py runserver)?

Yes, the development server runs without issue.

(venv) My-MacBook-Pro:mysite Me$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks…

System check identified no issues (0 silenced).
May 09, 2020 - 10:43:04
Django version 3.0.6, using settings ‘mysite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

So, I did the same as you. I started over from scratch and the new test suite is running fine, the old is still broken and I’m still not sure what is going on with that. :confused:

Something is different. I just don’t know what that is. I would say that it’s best to continue now that you have things working again. Sorry I couldn’t pinpoint what the problem was!

-Jorge

It’s fine. I greatly appreciate the attempt and the help. I’m just crossing my fingers every time I run a test, hoping that Django runs it without error lmao. I’m new to this whole thing —programming, that is — and I’ve been trying out the TDD approach. It helps me stay focused and on task… So if I can’t run test, I’m DOA lmao.

Thanks.

@amorestperpe
If you’d like to become more confident about what’s happening and revisit the “broken” project, I found something that might explain the issues you’re experiencing.

Look at the second answer in this SO thread, from user ‘Samuel’: https://stackoverflow.com/questions/40206569/django-model-doesnt-declare-an-explicit-app-label

He describes that he experienced a similar issue to what you’re getting as long as he had an __init__.py file in his project/root directory. I didn’t catch it first in the screenshot in your second post here, but you have the same thing. There’s an __init__.py file right above the db.sqlite3 and manage.py files.

I’m also working my way through the official tutorial (again). I just tried adding a __init__.py file to the root directory and bam, running python manage.py test produces ‘ImportError: Failed to import test module: official_tutorial.polls’. If I remove (rm __init__.py) the file and run python manage.py test again, everything’s back to normal.

I don’t know what exactly Django does in the background which causes this behavior, but apparently it’s really confused by the root directory being turned into a package (which is what __init__.py does).

7 Likes

Good catch! When I get a chance I’m going to try and figure out why that is.

-Jorge

I had the same issue and deleting init.py ended up solving it, thanks!

Really helpful. Thanks for that! We had the same issue

The __init__.py file is most likely needed. What would be a solution without deleting the file? Is this a bug?