User Tools

Site Tools


python:servingcsstest

SERVING CSS FILES FOR A DJANGO POWERED SITE

suited for test environments
22 June 2009

Django itself doesn’t serve static (media) files, such as images, style sheets, or video. Only for test purposes, use this:

CREATE THE DIRECTORY FOR YOUR CSS FILES

Create the directory who will contain the css files, for example /media inside your project main folder (or in another location, doesn't matter)

SET UP settings.py

MEDIA_ROOT = '<full path to /media directory>'
MEDIA_URL = '/static_media/'  # used in the templates files

Also, make sure that you have in settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",)

SET UP urls.py

Now, modify urls.py to serve the css files as needed:

# we use this trick to prevent it slip into production environment
if settings.DEBUG:
    urlpatterns += patterns('django.views.static',
        (r'^static_media/(?P<path>.*)$', 
            'serve', {
            'document_root': settings.MEDIA_ROOT,
            'show_indexes': True })
         ,)

Don't forget to include

from django.conf import settings

if you didn't so already.

ACCESS THE CSS

Now in the templates you can access the css file as:

<link rel="stylesheet" href="{{ MEDIA_URL }}style.css" type="text/css" media="screen">

MEDIA_URL will be substituted here by the value from the settings file. Very convenient if you move to production environment; all you need if to change in one place, rather than in a dozen, if you hardcoded the URL inside the templates.

python/servingcsstest.txt · Last modified: 2013/03/16 17:41 (external edit)