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

16 Oct


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!

Advertisement

Tags: , , ,

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

  1. James Tauber October 16, 2009 at 2:37 pm #

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.