django project directory structure and the python path

情到浓时终转凉″ 提交于 2019-12-20 09:25:31

问题


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.

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

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.

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

to help reusablility

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']

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

works ok

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.

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


回答1:


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'))


来源:https://stackoverflow.com/questions/3856891/django-project-directory-structure-and-the-python-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!