Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find unused template variables in Django

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.

like image 377
Kimvais Avatar asked Aug 10 '12 11:08

Kimvais


People also ask

What does {% %} mean in Django?

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.

What is context_ processors in Django?

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.

What is a context dictionary in Django?

A Context is a dictionary with variable names as the key and their values as the value.


1 Answers

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]
like image 184
Mariusz Jamro Avatar answered Sep 17 '22 15:09

Mariusz Jamro