导入自定义Django应用程序模块时出现ModuleNotFoundError

时间:2019-06-03 13:08:48

标签: django exception import module

我目前正在尝试在我的项目中创建自定义Django应用。我正在尝试从同一项目中的另一个目录访问某些模型,但无法从应用程序的模块中导入任何内容。

我在Stackoverflow上研究了许多问题,但都没有碰运气。我尝试过手动编辑sys.path。而且我也尝试过弄乱settings.py文件。

当前目录:https://gyazo.com/fe75655bd3296c47aaa36f5a10c92dfb

我正在尝试在我的bot应用程序的titandash目录中运行以下导入。

from titanbot.titandash.models.queue import Queue

我尝试用sys.path修复的问题是这样的:

import os
import sys

cwd = os.getcwd().split("\\")

if cwd not in sys.path:
    sys.path.append("\\".join(cwd))
if cwd[:-1] not in sys.path:
    sys.path.append("\\".join(cwd[:-1]))

sys.path.append("\\".join(cwd + ["titandash"]))

我希望我的模块可以从任一目录来回导入,以在其他地方使用。

  File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\urls.py", line 3, in <module>
    from .views import dashboard, project_settings
  File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\views.py", line 3, in <module>
    from .utils import start
  File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\utils.py", line 2, in <module>
    from .models.queue import Queue
  File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\models\queue.py", line 6, in <module>
    from titandash.bot.core.bot import grab_functions
  File "C:\Users\Brett\repos\tt2_py\titanbot\titandash\bot\core\bot.py", line 11, in <module>
    from titanbot.titandash.models.queue import Queue
ModuleNotFoundError: No module named 'titanbot.titandash'

注意:尝试在本地./manage.py runserver

上启动我的Django服务器时,会引发此堆栈。

1 个答案:

答案 0 :(得分:0)

titandash目录位于项目目录(包含manage.py的目录)中,Python目录中也是如此。因此,导入应为from titandash.models.queue import Queue,不带前缀titanbot