How to serve media with Django’s static serve only when using runserver


This is something that’s bugged me for a while. I like to develop my Django code locally, and to serve the media, I have to add a static serve line to my urls.py file. This can cause a few problems. The first is obvious, when you pull from your repository your server is also going to follow this directive slowing down your site to the speed of a ruby website (sorry, it was too easy). The second problem is: maybe your server doesn’t serve media from the same directory as you do locally!

There’s a couple easy fixes for this. The first is to use a DEBUG switch:

from django.conf import settings
if settings.DEBUG:
    urlpatterns += patterns('', url(r'^media/(.*)$', 'django.views.static.serve', kwargs={'document_root': os.path.join(settings.PROJECT_PATH, 'media')}), )

But I’m the type of guy who has forgotten to change DEBUG to false on the production server (I know I know!! This is the reason I do this).

So here’s my solution. If you detect runserver, then use django’s static serve. (I stole this idea from my friend and coworker Chris Poyzer):

import sys
if 'runserver' in sys.argv or 'runserver_plus':
    urlpatterns += patterns('', url(r'^media/(.*)$', 'django.views.static.serve', kwargs={'document_root': os.path.join(settings.PROJECT_PATH, 'media')}), )

If you don’t use runserver_plus yet which is part of django extensions, you need to. Upon hitting an error, it shows you a debug page (like usual) but with an inline python terminal in the browser!

Magical!

One Response to How to serve media with Django’s static serve only when using runserver

  1. If you forget to change DEBUG in production, you have bigger problems that serving static files!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>