[Answered ]-Easiest Way to Use Django Static Url Versioning?

2👍

Though I’m not familiar with the steps to integrate with Cloudfront, you can use Django’s CachedFileStorage to generate your assets with the md5 hash appended to the filename. This provides that anytime you rev a file you, you’ll generate a new unique asset.

All you need to do is set

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

and run manage.py collectstatic

This will create the assets in the folder that you collectstatic output to (STATIC_ROOT). I presume from here you upload this to Cloudfront. Your STATIC_URL I presume also points to Cloudfront.

In your templates, instead of putting references like {% STATIC_URL %}/asset.extension you use

{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />

This will map the asset appropriately to the correct asset.

See the documentation on CachedFileStorage to learn more, but it’s a pretty handy thing that’s baked into Django but not turned on by default. It does exactly what you want in making sure you always serve fresh assets and not returning stale js, css, or images.

Leave a comment