How do I delete a cached template fragment in Django?
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 cachefrom django.core.cache.utils import make_template_fragment_key# cache key for {% cache 500 sidebar username %} templatetagkey = 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.
If you could afford to empty memcached entirely, run flush_all
cmd or simply
from django.core.cache import cachecache.clear()
Or else you have to generate the cache-key manually. The timeout
will not be refreshed until the key is expired.
Prior to Django 1.6, the cache
template tag built its cache keys more-or-less in the body of the tag's definition (see here). From 1.6 onward, template fragment cache keys have been built using the django.core.cache.utils.make_template_fragment_key
function (see here).
In any case, you can delete a specific cached fragment by using or defining make_template_fragment_key
to get its cache key like so:
from __future__ import unicode_literalsimport hashlibfrom django.core.cache import cachefrom django.utils.encoding import force_bytesfrom django.utils.http import urlquoteTEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s'def make_template_fragment_key(fragment_name, vary_on=None): if vary_on is None: vary_on = () key = ':'.join(urlquote(var) for var in vary_on) args = hashlib.md5(force_bytes(key)) return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())def delete_cached_fragment(fragment_name, *args): cache.delete(make_template_fragment_key(fragment_name, args or None))delete_cached_fragment('my_fragment', 'other', 'vary', 'args')
This code is directly copied from the django codebase so this license and copyright applies.