Show undefined variable errors in Django templates?

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.


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.


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