First, consider some of the premises. I use the following "trick" to prevent unwanted cache cache of static files (CSS, JS, etc.):
<script src="{{ STATIC_URL }}js/utils.js?version=1302983029"></script>
When the version line changes the next time the page loads, it forces the browser to retrieve the static file from the server again. (Google css caching) for articles about this trick.)
I want the browser to get the latest version of the static file, but I also want to enable browser caching when the file has not changed. In other words, I want the version line to change if and only if the static file has been updated. I would also like to automatically generate a version string.
For this, I use the last modified time of the static file as the version string. I am making a special template tag for this:
<script src="{% versioned_static 'js/utils.js' %}"></script>
And this is how the template tag works:
import os.path from django import template from django.conf import settings class VersionedStaticNode(template.Node): ... def render(self, context):
To get a static file with the last modified time, I need to know its path to the file on the system. I get this file path by attaching settings.STATIC_ROOT and the relative file path from this static root. This is good and good for a production server, since all static files are collected in STATIC_ROOT .
However, on the development server (where the manage.py runningerver command is used), static files are not collected in STATIC_ROOT . So, how do I get the path to a static file when working in development?
(To clarify my purpose: the caching situation I want to avoid is a browser that uses a mismatch between the new HTML and the old CSS / JS. In production, this can be very confusing for users, in development it can confuse me and other developers, and makes us refresh pages frequently / clear browser cache.)