How do I delete a cached template fragment in Django?

dangerChihuahua007 picture dangerChihuahua007 · May 28, 2012 · Viewed 9.6k times · Source

Previously, I had set up a cached chunk of HTML in my Django template as follows.

{% load cache %}            
    {% cache 10000 courseTable %} <!-- Cached HTML --> {% endcache %}

Now, I have updated this cached content and want to refresh it. I tried changing the time to no avail:

{% load cache %}            
    {% cache 0 courseTable %} <!-- Updated Cached HTML --> {% endcache %}

In this case, the page still displays the old cached HTML.

I also tried removing the template tags associated with caching and reinserting them. However, in this case, the content just reverts to the originally cached content after I reinsert the cache template tags.

What can I do? I do not want to wait about 2 hours to reload my cache.

Answer

Jordi picture Jordi · Mar 9, 2017

For Django 1.6+ and from the Django Documentation you could just generate the key of the partial you're looking for and delete it:

from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key

# cache key for {% cache 500 sidebar username %} templatetag
key = make_template_fragment_key('sidebar', [username])
cache.delete(key) # invalidates cached template fragment

You just need to call make_template_fragment_key with your previously defined courseTable argument.