Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show undefined variable errors in Django templates?

Tags:

How can I ask Django to tell me when it encounters, for example, an undefined variable error while it's rendering templates?

I've tried the obvious DEBUG = True and TEMPLATE_DEBUG = True, but they don't help.

like image 338
David Wolever Avatar asked Nov 29 '10 02:11

David Wolever


3 Answers

Put this in your debug settings:

class InvalidString(str):
    def __mod__(self, other):
        from django.template.base import TemplateSyntaxError
        raise TemplateSyntaxError(
            "Undefined variable or unknown value for: \"%s\"" % other)

TEMPLATE_STRING_IF_INVALID = InvalidString("%s")

This should raise an error when the template engine sees or finds an undefined value.

like image 107
slacy Avatar answered Oct 29 '22 01:10

slacy


According to the django documentation, undefined variables are treated as ''(empty string) by default. While in if for regroup, it's None. If you are going to identify the variable undefined, change TEMPLATE_STRING_IF_INVALID in settings. '%s' makes the invalid variable to be rendered as its variable name, in this way, u can identify easily. how-invalid-variables-are-handled

like image 33
wliao Avatar answered Oct 29 '22 03:10

wliao


How to log a warning on undefined variable in a template

It seems that Django relies on undefined variables being a simple empty string. So instead of changing this behaviour or making it throw an exception, let's keep it the same but have it log a warning instead!

In your settings.py file:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # ...
        'OPTIONS': {
            # ...
            'string_if_invalid': InvalidStringShowWarning("%s"),
        },
    }
]

(string_if_invalid replaces TEMPLATE_STRING_IF_INVALID in newer Django versions.)

And further up, you'll need to define the InvalidStringShowWarning class, making it behave while logging a warning:

class InvalidStringShowWarning(str):
    def __mod__(self, other):
        import logging
        logger = logging.getLogger(__name__)
        logger.warning("In template, undefined variable or unknown value for: '%s'" % (other,))
        return ""

    def __bool__(self): # if using Python 2, use __nonzero__ instead
        # make the template tag `default` use its fallback value
        return False

You should be able to see the warning in the output of python manage.py runserver.

like image 23
Flimm Avatar answered Oct 29 '22 03:10

Flimm