[Django]-How to make Django template raise an error if a variable is missing in context

26👍

There is a Django Snippet which provides a solution:

# settings.py
class InvalidVarException(object):
    def __mod__(self, missing):
        try:
            missing_str=unicode(missing)
        except:
            missing_str='Failed to create string representation'
        raise Exception('Unknown template variable %r %s' % (missing, missing_str))
    def __contains__(self, search):
        if search=='%s':
            return True
        return False

TEMPLATE_DEBUG=True
TEMPLATE_STRING_IF_INVALID = InvalidVarException()

0👍

You can easily switch template backend to jinja2 to get this.

Step 0: add jinja2 to your Pipfile or requirements.txt

Step 1:
in settings.py change TEMPLATES to look like this:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'APP_DIRS': True,
        'OPTIONS': {
            'undefined': jinja2.StrictUndefined
        },
    },
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        ...

Step 2: rename your templates directory to jinja2

Step 3: (maybe not needed, depends on what you use in templates) update your templates according to https://jinja.palletsprojects.com/en/2.10.x/switching/#django

Leave a comment