django项目目录结构和python路径 [英] django project directory structure and the python path
问题描述
我正在尝试从一开始就开发我的django项目的最佳设置,我无法让所有内容在目录结构中很好地播放。我已经设置了virtualenv(在本示例中为env),以便我可以为每个django项目部署一个干净的空python环境。
I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty python environment for every django project.
基本结构如下: p>
The basic structure is as follows:
/env/
/bin
/db <--- Django DB
/downloads
/lib
/static <--- Where css/imgs/js etc is served from
/project/ <--- Django root
/__init__.py
/settings.py
/manage.py
/appsfolder/
/appname/
/__init__.py
/models/
/__init__.py
/somemodel.py
/urls/
/__init__.py
/someurl.py
/views/
/__init__.py
/someview.py
这是基本布局;我希望每个项目都有一个用于应用程序的目录,并且在每个应用程序中都有一个用于模型,视图和URL的单独的文件夹。
This is the basic layout; I want each project to have a directory for applications, and in each application have a separate folder for models, view and urls.
我遇到的问题是python路径以及模块的处理方式。
The problem I am having is with the python path and how the modules are handled.
在应用程序中,我不想在导入模型时引用该项目,即我应该使用:
Within an application, I don't want to have to refer to the project when importing models i.e I should be using :
import appname.models.modelname
not :
import projectname.models.modelname
以帮助可重用
在models目录中,我有以下 init .py
In the models directory, I have the following init.py
from model1 import ModelName1
from model2 import ModelName2
from model3 import ModelName3
__all__ = ['ModelName1', 'ModelName2', 'ModelName3']
但是当我尝试使用单独的url文件(在/appname/urls/urlfile.py中),并导入如下所示的模型:
But when I try to use a separate url file (in /appname/urls/urlfile.py) and import the models like the following:
from appname.models.somemodel import ModelName
我得到一个模块未找到错误。
I get a "module not found" error.
while:
from appsfolder.appname.models.somemodel import ModelName
工作正常
我推测是因为应用程序不是直接在python路径上,而是在一个名为appsfolder的子文件夹中,但我不知道如何解决这个问题,同时保持所有可重用的和相对的。
I presume this is because the application is not directly on the python path, instead it is in a subfolder called appsfolder, but I'm not sure how to go about fixing this, while keeping everything reuseable and relative.
我知道一个解决方案是将所有应用程序直接放置在站点包下的python路径上,但我不太喜欢这个想法,因为我认为应用程序应该在项目中,如果您使用的是virtualenv的
I know one solution is to put all apps directly on the python path under site-packages, but I don't really like this idea, as I think that the applications should be in the project if you are using virtualenv's
推荐答案
您可以将以下内容放在设置中。 py
将您的 appsfolder
添加到您的 PYTHONPATH
:
You can put the following in your settings.py
to add your appsfolder
to your PYTHONPATH
:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder'))
这篇关于django项目目录结构和python路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!