I have cache tag in the base template:
{% cache 100000 categories %}
Categories output
{% endcache %}
When I add new category through Django admin, I want invalidate this cache:
class CategoriesAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(CategoriesAdmin, self).save_model(request, obj, form, change)
cache.delete('categories')
But the cache is stay valid! What is wrong?
That’s because the actual key is not “categories”, but rather one that’s dynamically constructed by Django using the following:
See: https://code.djangoproject.com/browser/django/tags/releases/1.3.1/django/templatetags/cache.py
In general, the key is going to be in the format:
template.cache.categories.[hexdigest]. So the tricky part is figuring out the hexdigest part.I found the following Django snippet (in the comments), which looks like it should still work (from 2009):
Since you’re not passing any variables to vary on to the templatetag, you can call that with just:
invalidate_template_cache('categories'). Otherwise, you’d need to pass in a list of all the variables the template tag varies on as the second argument.