User Tools

Site Tools



suited for production environments
07 December 2008

Django itself doesn’t serve static (media) files, such as images, style sheets, or video. It leaves that job to whichever Web server you choose. To make this happen, follow the instructions:

We'll be using an apache webserver installed on the same machine as the django powered site.


1. Create the directory where the css files will reside

Let's assume that our project is called smallsite. We'll create a general folder to keep all the media files in wwwroot of our apache webserver, called django_media and inside this, a subfolder for our smallsite project called itself, smallsite.

So, we'll have…

mkdir /var/www/html/django_media/smallsite
chown apache.apache /var/www/html/django_media/smallsite

2. Populate the css folder with files

Inside our newly created css folder, we'll place base.css for example, which it'll be called later from our base template.

ls -l /var/www/htdocs/django_media/smallsite/
-rwxrwxr-x 1 apache    apache 83 2008-12-07 13:05 base.css

3. Configure the httpd server (in our case, apache) to take care of these files

Apache must be configured with mod_python.. In httpd.conf we must have

LoadModule python_module lib/httpd/modules/
# django python part

<Location "/">
    SetHandler python-program
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE smallsite.settings

<Location "/django_media">
    SetHandler None

Don't forget to restart the apache webserver!

4. Configure the django project to request such file from apache webserver

In under smallsite project:

# Absolute path to the directory that holds media.
# Example: "/home/media/"
MEDIA_ROOT = '/var/www/htdocs/django_media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "", ""
# MEDIA_URL = '/static_media/'
MEDIA_URL = 'http://localhost/django_media/smallsite/'

Check also for the following section in this file:


and then, in our templates, for example base.html, we can use to insert a css file:

    <link rel="stylesheet" href="{{ MEDIA_URL }}base.css" />

MEDIA_URL will be replaced by the value from the if you've put the TEMPLATE_CONTEXT_PROCESSORS section as shown above.

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