===================================
Outputting static files with Django
===================================

This document explains how to serve static files using Django.

Django provides you with an easy to use view to serve static content
such as images or ``CSS`` files.

.. admonition:: Note

    Add some warning about using this only in development or whatever your
    policy will be on this.

See `the Django overview`_ for a quick introduction to URL configurations; this
document will continue from there.

.. _`the Django overview`: http://www.djangoproject.com/documentation/overview/#design-your-urls

The static view
===============

Here's the example from that overview::

    from django.conf.urls.defaults import *

    urlpatterns = patterns('',
        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.articles.year_archive'),
        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.articles.month_archive'),
        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'myproject.news.views.articles.article_detail'),
    )

To serve static content, create a directory in a location of your choice
to contain all your desired files and subdirectories. Now modify your
URLconf similar to the following::

    urlpatterns = patterns('',
        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.articles.year_archive'),
        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.articles.month_archive'),
        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'myproject.news.views.articles.article_detail'),
        (r'^media/(?P<path>.*)', 'django.views.static.serve', {'document_root' : '/path/to/your/files/', 'show_indexes':True}),
    )

This will serve static content from your chosen directory and its subdirectories
for all URLs beginning with /media. You must provide the ``document_root`` parameter
to indicate where these files are to be found. The ``show_indexes`` parameter
is optional, but if set to ``True``, the view will show a basic index of all the
files in a given directory.

If you would like to create your own template to customize the index view,
you may create a template named ``static/directory_index``.

This example of a ``static/directory_index`` template is identical to the default
incuded with Django::

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="en-us" />
        <title>Index of {{ directory }}</title>
      </head>
      <body>
        <h1>Index of {{ directory }}</h1>
        <ul>
          {% for f in file_list %}
          <li><a href="{{ f }}">{{ f }}</a></li>
          {% endfor %}
        </ul>
      </body>
    </html>

