Django project directory structure and python path

I have been trying to get the best possible setting for developing my django project from the very beginning, and I am having problems getting everything good in the directory structure. I installed virtualenv (env in this example) so that I can deploy a clean empty python environment for each 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 main layout; I want each project to have a directory for applications, and each application has a separate folder for models, views, and URLs.

The problem I ran into is related to the python path and how the modules are processed.

In the application, I do not want to refer to the project when importing ie models, I should use:

 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 as follows:

 from appname.models.somemodel import ModelName 

I get a "module not found" error.

while:

 from appsfolder.appname.models.somemodel import ModelName 

works fine

I assume this is because the application is not directly in the python path, instead it is in a subfolder called applicationfolder, but I'm not sure how to do this, while preserving everything that is repeating and relative.

I know that one solution is to place all applications directly in the python path in site packages, but I do not really like this idea, since I think that applications should be in the project if you use virtualenv

+6
python django django-models pythonpath
source share
1 answer

In settings.py you can add the following appsfolder to < PYTHONPATH :

 import os import sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder')) 
+14
source share

All Articles