Django static
June 28, 2011
I wanted to reduce the size of some javascript on my site. I did this using django-static
.
Dependencies
This depends on the slimmer project, install this using:
# easy_install slimmer
Source Files
I downloaded the source for django_static and added it to my project path. I then added
'django_static',
to my INSTALLED_APPS
and
DJANGO_STATIC = True
to my settings.py
.
Template
In my Django template, I added
{% load django_static %}
at the top, and then changed the reference to the javascript file from:
<script src="/site_media/js/playback.js"></script>
to
<script src="/site_media{% slimfile "/js/playback.js" %}"></script>
I found that if I included site_media
in the path inside the template tag, I got a warning in the Django test server console:
/path/to/project/django_static/templatetags/django_static.py:451: UserWarning: Can't find file /site_media/js/playback.js in /path/to/project/site_media/
where MEDIA_ROOT
is set to:
MEDIA_ROOT = '/path/to/project/site_media/'
Doing a view source on the page now shows a script path of:
<script src="/site_media/js/playback.1309294215.js"></script>
Security
As it stands, this requires write access to the filesystem where the web files are stored. To get around this, we can specify another directory to store the symbolic links in.
In your settings.py:
DJANGO_STATIC_SAVE_PREFIX = "/var/tmp/site/django_static"
This needs to have write access by the user running the webserver.