python - Django 从另一个包导入另一个文件

标签 python django

我有以下文件夹结构

app/
app/helpers/
app/helpers/methodhelper.py
app/methods/
app/methods/method.py

and I'm trying to import a function from methodhelper.py inside method.py
so I tried the following:

import app.helpers.methodhelper
OR
from app.helpers.methodhelper import function1
OR
import helpers.methodhelper

and I get:

"No module named app.helpers.methodhelper" 

重要提示:helpers/__init__.py 已经存在

应该怎么做?

最佳答案

您的 Django 项目的默认路径位于项目的根目录(manage.py 文件所在的位置)。您可以将其下方的子目录添加到您的 PYTHONPATH(通过附加到 sys.path 轻松完成),或者您可以使用完整的模块路径导入该函数:

from projectname.app.helpers.methodhelper import function1

当我开始一个Django项目时,我总是添加

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

到我的 settings.py。此路径看起来类似于 /home/kyle/django_project_name/。里面直接是 manage.py

从那里,也在我的 settings.py 中,我包括:

sys.path.append(os.path.join(PROJECT_ROOT, 'django_project_name'))

这使得我的应用无需在模块路径中包含我的项目名称即可导入。

关于python - Django 从另一个包导入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530728/

相关文章:

python - AppRegistryNotReady : The translation infrastructure cannot be initialized

django 中间件只有 "process_response"当缺少斜杠时

python - 从 DataFrame 创建直方图(其中索引值是变量)

python - 将大量变量导入命名空间

python - 如何从 lxml.html.html5paser 元素标记内部删除 namespace 值

python - 如何使用新的 api 权限显示简单的 Instagram feed

python - 无法解析超链接关系的 URL

python - 如何编辑qtableview中的特定项目?

python - numpy 数组索引表示超出范围

python-3.x - 如何优化我的 Python 反向图像搜索以限制到特定域?