Thursday, January 20, 2011

Serving Django Admin CSS Files

The Django documentation says the following about deploying the admin module on Apache. The admin media files in this case are the CSS files that come with Django.

Note that the Django development server automagically serves admin media files, but this is not the case when you use any other server arrangement. You're responsible for setting up Apache, or whichever media server you're using, to serve the admin files.

The admin files live in (django/contrib/admin/media) of the Django distribution.

Here are two recommended approaches:

Create a symbolic link to the admin media files from within your document root. This way, all of your Django-related files -- code and templates -- stay in one place, and you'll still be able to svn update your code to get the latest admin templates, if they change.
Or, copy the admin media files so that they live within your Apache document root.

I tried the symlink route but it just would not work. I wanted to avoid putting the files under htdocs so I wouldn't have to remember to copy the files when I update Django.

I ended up getting it to work with the following modifications:

settings.py
------------
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
ADMIN_MEDIA_PREFIX = '/media/admin/'

/etc/apache2.conf
------------------
Alias /media/admin/ /local/apps/python27/lib/python2.7/site-packages/django/contrib/admin/media/

Remember to restart Apache. If you are not running Apache as root, you may have to adjust some permissions, but all in all this seems like a straightforward approach and I'm surprised it is not in the Django documentation.

1 comment:

  1. Also likely of interest:

    Sync media to CDNs (or possibly to your htdocs?)

    https://github.com/sunlightlabs/django-mediasync

    Static File helper, which is landing in Django 1.3

    http://django-staticfiles.readthedocs.org/en/latest/index.html

    ReplyDelete