Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django project directory structure and the python path

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

like image 915
Timmy O'Mahony Avatar asked Oct 04 '10 15:10

Timmy O'Mahony


1 Answers

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'))
like image 131
Bernhard Vallant Avatar answered Sep 18 '22 05:09

Bernhard Vallant