staticfiles.storage.ManifestStaticFilesStorage

class storage.ManifestStaticFilesStorage

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 storage backend automatically replaces the paths found in the saved files matching other saved files with the path of the cached copy (using the post_process() method). The regular expressions used to find those paths (django.contrib.staticfiles.storage.HashedFilesMixin.patterns) by default covers the @import rule and url() statement of Cascading Style Sheets. For example, the 'css/styles.css' file with the content

@import url("../admin/css/base.css");

would be replaced by calling the url() method of the ManifestStaticFilesStorage storage backend, ultimately saving a 'css/styles.55e7cbb9ba48.css' file with the following content:

@import url("../admin/css/base.27e20196a850.css");

To enable the ManifestStaticFilesStorage you have to make sure the following requirements are met:

  • the STATICFILES_STORAGE setting is set to 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
  • the DEBUG setting is set to False
  • you’ve collected all your static files by using the collectstatic management command
Changed in Django 1.10:

In older versions, you also had to use {% load static from staticfiles %} in your template. The static template tag ({% load static %}) now uses django.contrib.staticfiles if it’s installed.

Since creating the MD5 hash can be a performance burden to your website during runtime, staticfiles will automatically store the mapping with hashed names for all processed files in a file called staticfiles.json. This happens once when you run the collectstatic management command.

Due to the requirement of running collectstatic, this storage typically shouldn’t be used when running tests as collectstatic isn’t run as part of the normal test setup. During testing, ensure that the STATICFILES_STORAGE setting is set to something else like 'django.contrib.staticfiles.storage.StaticFilesStorage' (the default).

doc_Django
2016-10-09 18:39:41
Comments
Leave a Comment

Please login to continue.