How can I expire the django template cache key when receiving a signal?

In my homepage template, I use the caching function as follows:

{% cache 86400 my_posts %} {% get_latest_posts %} {% endcache %} 

When a new message appears, I would like to expire the cache key; eg:

 def clear_post_cache(): cache.delete('my_posts') post_save.connect(clear_post_cache, sender=Post) 

My problem is that the cache key is not available as "my_posts". How to find the key name?

+6
django caching templates
source share
3 answers

See how the cache key is created :

 args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest()) 

The key is a combination of the fragment name ( my_posts ) and the sum of the additional md5 arguments for the cache tag. Since you have no additional arguments, hexdigest is d41d8cd98f00b204e9800998ecf8427e (hash xd5 of the empty string). Therefore, the cache key must be

 template.cache.my_posts.d41d8cd98f00b204e9800998ecf8427e 

If you need a more general solution, this snippet may help.

+16
source share

Please note that the md5_constructor in the first line of the above Benjamin Volrendra example is deprecated. Current Version (November 2011):

 args = hashlib.md5(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on])) 
+3
source share
 from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key cache.delete(make_template_fragment_key('footer')) 
+2
source share

All Articles