Static Files in Django on Production and Development
Posted on September 22nd, 2008 by Greg Allard in Programming | Comments
For developing a django application, I’ve been using the webserver that comes with django. It’s great for development since there is no need to restart apache. The quick and easy way to server a static file with the django webserver is to use this in your urls.py:
urlpatterns = patterns('', ( r'^files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/django-proj/files'} ), # ... more url patterns )
Which worked great for testing things out, but it is definitely not a good idea to use this in a production environment. On the production server I set apache to not bother with mod_python for those directories so that django doesn’t have to do any processing.
Since I wanted to use the same files on each server, I didn’t want the static serve in the url patterns on production. To add more patterns to urlpatterns, you can do urlpatters += patterns(”, to add more. I also added the file locations into settings.py since they would be different for other developers. Using if hasattr(settings, ‘STATIC_FILE_LOCATION’): I was able to keep the urlpatterns in the right format whether it’s in a production or development environment.
An example of what I’m using:
from django.conf.urls.defaults import * from django.conf import settings # basic urls urlpatterns = patterns('', (r'^logout/', 'myproject.user.views.logout'), (r'^login/', 'myproject.user.views.login'), ) # if on a development machine if hasattr(settings, 'STATIC_FILE_LOCATION'): urlpatterns += patterns('', (r'^files/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_FILE_LOCATION}), ) # application urls urlpatterns += patterns('', # add new applications below here (r'^user/', include('myproject.user.urls')), # end applications # the index (r'^$', 'myproject.user.views.index'), )