- Author:
- joao.coelho
- Posted:
- November 16, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 0 (after 0 ratings)
This is a custom template tag that clears the cache that was created with the cache tag.
{% load clearcache %}
{% clearcache [fragment_name] [var1] [var2] .. %}
Create app/templatetags folder with init.py and copy code into clearcache.py file.
polls/
templatetags/
__init__.py
clearcache.py
Based on django.templatetags.cache. See Django docs on custom template tags
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | from django import template
from django.template import resolve_variable
from django.core.cache import cache
from django.utils.http import urlquote
from django.utils.hashcompat import md5_constructor
register = template.Library()
class ClearCacheNode(template.Node):
def __init__(self, fragment_name, vary_on):
self.fragment_name = fragment_name
self.vary_on = vary_on
def render(self, context):
# Build a unicode key for this fragment and all vary-on's.
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())
cache.delete(cache_key)
return ''
def clearcache(parser, token):
"""
This will clear the cache for a template fragment
Usage::
{% load clearcache %}
{% clearcache [fragment_name] %}
This tag also supports varying by a list of arguments::
{% load clearcache %}
{% clearcache [fragment_name] [var1] [var2] .. %}
The set of arguments must be the same as the original cache tag (except for expire_time).
"""
try:
tokens = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires at least one argument" % token.contents.split()[0]
return ClearCacheNode(tokens[1], tokens[2:])
register.tag('clearcache', clearcache)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.