Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache busting in Django 1.8?

Tags:

python

django

I'm using Django 1.8 and I want to add a parameter to my static files to cache bust.

This is what I'm doing right now, setting a manual parameter:

<link href="{% static 'css/openprescribing.css' %}?q=0.1.1" rel="stylesheet">

But I feel there must be a better way to update the parameter.

I guess it would be a bit neater to have a setting passed through the template (and that would save having to update it in multiple places).

But what would be really nice is if Django could update it automatically for me.

The notes on django-cachebuster suggest that it's now possible to do this automatically in staticfiles, but I can't find anything in the staticfiles docs about it.

Anyone know a way to do this?

like image 515
Richard Avatar asked Jun 19 '15 10:06

Richard


1 Answers

Yes this can be done automatically with contrib.staticfiles. There are two additional provided storage classes which will rename files using a hash. These are documented here: ManifestStaticFilesStorage and CachedStaticFilesStorage

From the docs:

A subclass of the StaticFilesStorage storage backend which stores the file names it handles by appending the MD5 hash of the file’s content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css.

The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.

The main difference is

CachedStaticFilesStorage is a similar class like the ManifestStaticFilesStorage class but uses Django’s caching framework for storing the hashed names of processed files instead of a static manifest file called staticfiles.json. This is mostly useful for situations in which you don’t have access to the file system.

To enable them you need to change your STATICFILES_STORAGE setting is set to 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' or 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'. The file names are only changed when DEBUG=False as it would be in production.

like image 99
Mark Lavin Avatar answered Oct 09 '22 00:10

Mark Lavin