Sunday, December 14, 2008

serve static files from the media folder using the django runserver command

It's never a good idea to serve files using the django manage.py runserver task but it comes in handy during developement when you don't want to setup a whole webserver like lighttpd or apache just for your sandbox.

SO I checked the documenation located at: http://docs.djangoproject.com/en/dev/howto/static-files/

and it walks you through how to setup the Django development script to serve files from the media folder using a secret "serve" view built into Django.

to turn it on you just drop in the route for it in the URLconf (ie urls.py) config file into the urlpatterns array:

urlpatterns = patterns('',
(r'^site_media/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
)


the above example uses a custom static variable from the settings.py file. If your going to do that make sure you import settings.py at the top your urls.py.

from django.conf import settings
...
(r'^site_media/(?P.*)$', 'django.views.static.serve',

{'document_root': settings.STATIC_DOC_ROOT}),

An even smarter way to do things is to only serve static files when you are in debug (dev) mode by including the followling logic to check for debug=true around your route definition:

if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.DEV_MEDIA_ROOT, 'show_indexes': True}),
)


That's pretty much it, except that you need to remember that if your going to use /media/ as the directory to serve your static files from to also change the name of the media folder that the Admin scaffolding defaults to. I started out with the scaffolding media path set to /media/ and it was not letting the route defined above execute. Took me forever to figure out that the two media folders were conflicting. SO in you settings.py make sure that ADMIN_MEDIA_PREFIX is set to something other than /media/ maybe something like:

ADMIN_MEDIA_PREFIX = '/admin_media/'

0 Comments:

Post a Comment

<< Home