djangodjango-templatesdjango-cachepython-memcached

How can explicitly reset a template fragment cache in Django?


I am using Memcache for my Django application.

In Django, developers can use template fragment caching to only cache a section of a template. https://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching

I was wondering if there is a way to explicitly change the value of a template fragment cache section say in views.py. For instance, could one use a method akin to cache.set("sidebar", "new value") except for a template fragment cache?

Thank you for your help.


Solution

  • In theory, yes. You first have to create a template cache key in the same pattern used by Django, which can be done with this snippet of code:

    from django.utils.hashcompat import md5_constructor
    from django.utils.http import urlquote
    
    def template_cache_key(fragment_name, *vary_on):
        """Builds a cache key for a template fragment.
    
        This is shamelessly stolen from Django core.
        """
        base_cache_key = "template.cache.%s" % fragment_name
        args = md5_constructor(u":".join([urlquote(var) for var in vary_on]))
        return "%s.%s" % (base_cache_key, args.hexdigest())
    

    You could then do something like cache.set(template_cache_key(sidebar), 'new content') to change it.

    However, doing that in a view is kind of ugly. It makes more sense to set up post-save signals and expire cache entries when models change.

    The above code snippet works for Django 1.2 and below. I'm not sure about Django 1.3+ compatibility; django/templatetags/cache.py will have the latest info.

    For Django 1.7, django/core/cache/utils.py has a usable function.