无法将文件从应用程序导入到另一个应用程序

not able to import a file from an app to another

我有一个结构如下的 Django 项目:

main_project

----main_project

<------库

<<--------exceptions.py

----project_a

----project_b

project_a 的 views.py 中,我正在尝试导入名为 libs 的文件夹 main_project 和来自 libs 的一个名为 exceptions.py 的文件,但我得到了错误
ImportError: No module named libs.exceptions

我的代码是:

from main_project.libs.exceptions import (
    APIException400,
    APIException405,
    APIException403,
    exception_handler_dispatcher,
)

有人可以告诉我我在这里缺少什么吗? 参考 答案我什至尝试过:

from main_project.main_project.libs.exceptions import (
        APIException400,
        APIException405,
        APIException403,
        exception_handler_dispatcher,
    )

但不起作用。

当您使用 from main_project.libs.exceptions 导入时,python 期望 main_project 是包,libsexceptions 是子模块。因此,这些目录中必须有一个名为 __init__.py 的文件。需要 init.py 文件才能使 Python 将目录视为包含包。如需进一步阅读,请参阅 here

您似乎忘记将 __init__.py 添加到 libs 目录。

The __init__.py is used to initialize Python packages. Check the documentation to better understand how things are working.

您的结构应如下所示:

    project/
    |   
    |-- __init__.py
    |   
    |-- module_a/
    |   |-- __init__.py
    |   |
    |   |-- file1.py
    |   |
    |   |-- file2.py
    |
    |-- module_b/
    |   |
    |   |-- __init__.py
    |   |
    |   |-- file1.py
    |   |
    |   |-- submodule/
    |   |   |--__init__.py
    |   |   |
    |   |   |-- file1.py