【发布时间】:2015-10-13 13:00:12
【问题描述】:
我在 django 项目的另一个应用程序中导入应用程序时遇到问题。 我知道有几个关于这个主题的问题/asnwsers,相信我我读过很多,甚至一些关于 python 导入的。
这是我的项目树(我会放真正的文件夹名称):
was/ # full path from my computer /home/user/project/was
....was/ #django project created by django-admin startproject 'was'
....manage.py
....artists/ #first app
....migrations/
....templates/
....__init__.py
....other_python_files.py
....crew/ #second app
....migrations/
....templates/
....__init__.py
....some_files.py
....was/ # folder containing settings.py, main urls.py
....__init__.py
我的第一个项目(/home/user/project/was)包含 virtualenv 生成的文件夹(python3.4)。
我检查了我的 python 路径 sys.path 和我在 Pycharm 中的项目结构,有 /home/user/project/was。
当我在 PyCharm 中执行此操作时,我的自动补全工作正常:
from ..crew.models import MyClass #here i'm in a artists app file
但我收到了ValueError :attempted relative import beyond top-level package when import app
现在,同样的场景,在艺术家应用程序中导入一个船员班,但是:
from was.crew.models import MyClass
自动补全在 pycharm 中运行良好,但这次我得到了经典的 ImportError :no name was.crew。
我通过在我的 settings.py 中添加这一行来找到解决方案:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR)) # add this line
请注意,BASE_DIR 已存在于设置中。
现在我可以这样做了:
from crew.models import MyClass
在这里我没有出错(更改 Pycharm 中的一些设置以使自动完成工作)。
这行得通,但我真的很想知道为什么我必须添加这一行以及为什么我的两次第一次尝试都不起作用。
我对包、pythonpath 等有点迷茫(这就是我在架构中指定所有 __init__.py 文件的原因)。
不应该 from ..anotherapp.models import Class 在 settings.py 中不拉皮条就可以正常工作吗?
无论如何,我应该保留我的解决方案还是不是一件好事?
提前感谢您的任何回复。
PS:请注意,我已经尝试在我的第一个和第二个文件夹中有 __init__.py 文件,但没有成功。
【问题讨论】:
标签: python django python-3.x python-import