我有以下文件夹结构
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/