User Tools

Site Tools


python:servingcsstest

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:servingcsstest [2013/03/16 17:41] (current)
Line 1: Line 1:
 +==== 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 ===
 +
 +
 +<code python>
 +MEDIA_ROOT = '<​full path to /media directory>'​
 +MEDIA_URL = '/​static_media/' ​ # used in the templates files
 +</​code>​
 +
 +Also, make sure that you have in settings.py
 +
 +<code python>
 +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",​)
 +</​code>​
 +
 +
 +=== SET UP urls.py ===
 +
 +Now, modify urls.py to serve the css files as needed:
 +
 +<code python>
 +# 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 })
 +         ,)
 +</​code>​
 +
 +Don't forget to include
 +
 +<code python>
 +from django.conf import settings
 +</​code>​
 +
 +if you didn't so already.
 +
 +
 +=== ACCESS THE CSS ===
 +
 +
 +Now in the templates you can access the css file as:
 +
 +<code html>
 +<link rel="​stylesheet"​ href="​{{ MEDIA_URL }}style.css"​ type="​text/​css"​ media="​screen">​
 +</​code>​
 +
 +**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)