No module named… in Django proyect

Question:

I have a pretty standart Django project and i can’t find a way to import /middleware/utils/compare.py from /middleware/utils/request.py

This is the proyect tree:

|--middleware/
|  |--utils/
|  |  |--compare.py
|  |  |--request.py
|  |--__init__.py
|  |--asgi.py
|  |--settings.py
|  |--urls.py
|  |--views.py
|  |--wsgi.py
|--manage.py

Where __init__.py, asgi.py, settings.py, urls.py, wsgi.py have no major modifications. (__init__.py is empty)

# middleware/views.py
from .utils.request import requests # This line works fine
# middleware/utils/request.py
from compare import compare # ModuleNotFoundError: No module named 'compare'
from .compare import compare # Attempted relative import beyond top-level package pylint(relative-beyond-top-level)
# ^^^ This line absolutly breaks my code, but it runs
from utils.compare import compare # ModuleNotFoundError: No module named 'utils'
from .utils.compare import compare # ModuleNotFoundError: No module named 'middleware.utils.utils'

Note: compare.py has a function named compare, i also tried renaming it but had the same problems.

This might be obvious, but i run the proyect with python manage.py runserver

Asked By: André Kuljis

||

Answers:

Simply add empty __init__.py in utils folder.

And read more about it here:

https://docs.python.org/3/tutorial/modules.html#packages

Answered By: Maxim Danilov

Change your file tree like this,

|--middleware/
|  |--utils/
|  |--|__init__.py # Added this file
|  |  |--compare.py
|  |  |--request.py
|  |--__init__.py
|  |--asgi.py
|  |--settings.py
|  |--urls.py
|  |--views.py
|  |--wsgi.py
|--manage.py

And import like this,

from utils.compare import compare 
Answered By: Rahul K P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.