Working Ninja
2017-08-30T17:52:40
Prevent Caching Hell While Still Taking Advantage of Caching

Using the ManifestStaticFilesStorage storage backend alters the filename of our static files. For example, style.css becomes something like style.3d94ea84cd8a.css. When collectstatic is run and finds a file that has changed, the MD5 portion of the filename will be updated (style.3d94ea84cd8a.css -> style.1d74ea7349df.css). This prevents browsers and other caching technologies (e.g. Cloudflare) from referring to an outdated static file.

Here are the minimum settings / steps to get this going:

# settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static'),

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'staticfiles'),
]

After setup (and after updates to any files contained within STATICFILES_DIRS), make sure to run ./manage.py collectstatic. This is easy to forget!

More:
https://docs.djangoproject.com/en/stable/ref/contrib/staticfiles/#manifeststaticfilesstorage
https://docs.djangoproject.com/en/stable/ref/settings/#staticfiles-storage