Raise an exception or log when a Django template variable is invalid

django's template engine is tolerant, so calling a function or variable that doesn't exist on an object will make no exception. In such a case, it will render with an empty string instead of an exception.

This is a lot of behavior that is appreciated in the production environment, but it is also nice to get an error in the development environment. Also, even in a production environment, it should be possible to output a log even if it does not cause an error.

Until django1.8, it worked by the following method, but after that, the setting method has changed. stackoverflow.com:show-undefined-variable-errors-in-django-templates

You can now set a value for TEMPLATES.OPTIONS.string_if_invalid in settings.py. docs.djangoproject.com:How invalid variables are handled

Here, specify "What to display when accessing a template variable that does not exist". Basically, it is expected to set a character string, and if you enter % s, you can see the" accessed (non-existent) variable name ".

If you make the following settings here, you will be able to define the behavior of "when accessing a template variable that does not exist".

settings.py

class InvalidString(str):
    # "%s is ok" % undefined  :For string format operations__mod__Is called
    def __mod__(self, other):
        msg = "Undefined variable or unknown value for: %s" % other
        if TEST or IS_LOCAL:
            #Exception for development environment
            from django.template.base import TemplateSyntaxError
            raise TemplateSyntaxError(msg)
        else:
            #Log output if it looks like production
            import logging
            logger = logging.getLogger('strange')
            logger.info(msg)


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
            ],
            'string_if_invalid': InvalidString("%s"),  #Set here
        },
    },
]

__mod__ is usually int-like and writes the behavior when the remainder is calculated, If you define something like a string, it will be called during string format operations. In this case, ʻother` is accessed, but a variable name that does not exist is entered and called.

Recommended Posts

Raise an exception or log when a Django template variable is invalid
[Django] A memo when log was not
A program that automatically determines whether an animation or a photo is entered when a person's image is input [python]