Smarter Django project configuration
Two points
Generally we need different settings for Django project in development environment on localhost and on production environment. Settings may differ also across different development environments when application is developed by many programmers.
Project source is good to be stored in some VCS repository, so settings should also be stored there. Settings modifications that are common for different environments should be automatically applied after updating from repository.
How to
Here’s a couple of recipes on how to configure Django project in a bit smarter way.
1. Define settings template
Just make a copy of settings.py to settings_template.py and then import settings_template from settings:
from settings_template import *
Then you may override some settings, i.e. DUBUG flag or database settings etc.:
from settings_template import *
DEBUG = False
Note: now settings.py should not be stored in repository, but settings_template.py should be stored there.
2. Define paths based on project directory
I know many good programmers do that :) Add somewhere at start of settings, I mean settings_template.py:
import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
Now you can define media and template paths like this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
3. Configure serving static files
Django documentation offers to serve on not to serve static files depenging on DEBUG flag. Sometimes that may not be correct, as we may need debug mode on production environment, where static files are served by webserver.
I offer to use separate SERVE_STATIC flag in settings for this. So, here is urls.py example:
from django.conf import settings
# some urls config ...
if getattr(settings, 'SERVE_STATIC', False):
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL[1:] + r'(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT})
)
So, when I need to serve static files by development server, I just add SERVE_STATIC = True to settings.py.
Feedbacks
Please give a feedback, if it was useful or not. I hope it was :) If you have your own recipes on subject, you’re welcome to share links or snippets.