Home > Enterprise >  No module named... in Django proyect
No module named... in Django proyect

Time:10-03

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

CodePudding user response:

Simply add empty __init__.py in utils folder.

And read more about it here:

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

CodePudding user response:

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 
  • Related