简体   繁体   中英

No module named... in Django proyect

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

Simply add empty __init__.py in utils folder.

And read more about it here:

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM