Django从另一个包导入另一个文件 [英] Django importing another file from another package

查看:128
本文介绍了Django从另一个包导入另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下文件夹结构

I have the following folder structure


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

尝试从method.py中的methodhelper.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

我得到:

"No module named app.helpers.methodhelper" 

重要说明: helpers / __ init __。py 已经存在

应该怎么做?

How should this be done ?

推荐答案

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

Your Django project's default path is in the root directory of the project (where the manage.py file is). You can either add the sub directories below that to your PYTHONPATH (easily done by appending to sys.path) or you can import that function using the full module path:

from projectname.app.helpers.methodhelper导入功能1

启动Django项目时,我总是添加

When I start a Django project, I always add

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

到我的 settings.py 。此路径类似于 / home / kyle / django_project_name / 。直接在其中是 manage.py

to my settings.py. This path looks similar to /home/kyle/django_project_name/. Inside that directly is manage.py.

从此处开始,也是在我的设置中。 py ,我包括:

From there, also in my settings.py, I include:

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

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

This makes my apps importable without the need to include my project name in the module path.

这篇关于Django从另一个包导入另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆