Invalidate template fragment cache in Django 1.5

Django 1.5 does not have a utility method to delete template fragment cache, with arguments.

In order to achieve this, you must create a custom method:
from django.core.cache import cache
from django.utils.hashcompat import md5_constructor
from django.utils.http import urlquote

def invalidate_template_fragment(fragment_name, *variables):
args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
cache_key = 'template.cache.{0}.{1}'.format(fragment_name, args.hexdigest())

Example usage:
{% cache 259200 key_name %}
... cached content here ...
{% endcache %}

// note that "" is optional argument. You can use as many as you need

... and delete the cache:


In django 1.6+ you can do this more easy:
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key

key = make_template_fragment_key('key_name', [])


Popular posts from this blog

Compare integer variable in django templates

Top things to do after installing Manjaro KDE

PIP - upgrade all packages from requirements.txt (interactively)