Django: How to serve media files (CSS, images, javascript, etc)

Being new to both Python and Django, I was having some trouble setting up my project to serve static files.

Looking at the static serving docs, they seem to gloss over the main points but dont quite help get you there.

To get support for static file serving:

  • In "settings.py", import "os.path"

import os.path

  • Change "MEDIA_ROOT", "MEDIA_URL" and "ADMIN_MEDIA_PREFIX" to

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), "media")
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/' (anything other than media)

  • In "urls.py", include the following imports

from django.views.static import *
from django.conf import settings

  • And the following URL handler

# Required to make static serving work
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

Restart your server and it should be accessible from http://your.domain.com/media/something.css

*Edit 06/11/09*

If its still displaying a 404, check that "ADMIN_MEDIA_PREFIX" is not the same as "MEDIA_URL".

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog