Tuesday, March 22, 2011

Django Project Setup Conveniences

Whenever I start a new Django project, there are several common steps that I to help standardize my setups.

In settings.py...

I define a PROJECT_ROOT variable which contains the path to the project directory. 

This is useful for various settings in the setup.py:
import sys, os
PROJECT_ROOT = os.path.dirname(__file__)

I set my MEDIA_ROOT to be a path relative to the PROJECT_ROOT.  
Of course, I will need to create this directory on the filesystem. 
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '..','htdocs','media').replace('\\','/') + '/'

And I set a relative TEMPLATE_DIRS path.  I will need to make this directory as well.
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

Sometimes I add extra directories to the path so I can store specific packages within the project directory. (I might use this if I want to keep all related modules together).
sys.path.insert(0, os.path.join(PROJECT_DIR, "contrib"))
sys.path.insert(0, os.path.join(PROJECT_DIR, "src"))

I generally like to put admin media in the following location:
ADMIN_MEDIA_PREFIX = '/media/admin/'

Almost all the time, I install the following modules in INSTALLED_APPS:
'south', # django-south
'django_extensions', # django-command-extensions

In urls.py...


If I want to use the Django debug server, I'll set this near the top:
from django.conf import settings
urlpatterns = patterns('',)
if settings.DEBUG:
    urlpatterns = patterns('',
        (r'^media/(?P<path>.*)$', 'django.views.static.serve',
                   {'document_root': settings.MEDIA_ROOT}),
    )


No comments:

Post a Comment