I'm doing clean up on django code - my IDE can easily detect unused variables etc in Python code, but I haven't found a way to find unused template variables - it would be much easier to clean up the view code if I could find out what values in the context dictionary are not accessed by the templates.
Is there a tool for this?
EDIT: I am looking for an offline solution, a static code analysis tool or such. While the paranoid templates solution suggested below is better than nothing, it is not optimal because there are multiple {% if ... %}
branches in templates and futhermore, would require testing all the views (in all use cases) in order to find all the unreferenced variables.
This tag can be used in two ways: {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend. {% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template.
context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.
A Context is a dictionary with variable names as the key and their values as the value.
Try paranoid django templates solution:
class ParanoidContextProxy(object):
"""
This is a poor-man's proxy for a context instance.
Make sure template rendering stops immediately on a KeyError.
"""
def __init__(self, context):
self.context = context
self.seen_keys = set()
def __getitem__(self, key):
self.seen_keys.add(key)
try:
return self.context[key]
except KeyError:
raise ParanoidKeyError('ParanoidKeyError: %r' % (key,))
def __getattr__(self, name):
return getattr(self.context, name)
def __setitem__(self, key, value):
self.context[key] = value
def __delitem__(self, key):
del self.context[key]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With