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())
cache.delete(cache_key)

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

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

... and delete the cache:
invalidate_template_fragment('key_name', model_instance.pk)

 

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', [model_instance.pk])
cache.delete(key)

Comments

Popular posts from this blog

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

Improve font rendering for IntelliJ IDEA / Pycharm in Ubuntu