Django: registration template errors

When I make a mistake in the django template {{placeholder}}, I don't get the error, just an empty place in the output where the content was expecting. Is there a way to see something in my magazines when this happens, preferably using logging.warningor logging.error?

+4
source share
3 answers

The only thing Django provides for handling unknown context variables in TEMPLATE_STRING_IF_INVALID. You will need to crack the template engine a little deeper if you want better than this.

+2
source

Yes there is. Just add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.template': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}

roboslone, Django 1.9 . Django.

+1

In Django> = 1.8, TEMPLATE_STRING_IF_INVALIDdeprecated in favor of string_if_invalidc settings.TEMPLATES.

If you want to do a bit more than depend on messages DEBUGfrom the registrar django.template, you can trick the following code into django.template.base.FilterExpression.render():

if '%s' in string_if_invalid:
    return string_if_invalid % self.var

With a class like the following:

class InvalidString(object):
    def __mod__(self, other):
        log.error('Missing template variable: "%s"', other)
        # ... do other interesting things ... 
        return u''

    def __contains__(self, item):
        return item == '%s'

And set string_if_invalidto settings.TEMPLATES:

TEMPLATES = [{
    'OPTIONS': {'string_if_invalid': InvalidString()}
    # ...
}]
0
source

Source: https://habr.com/ru/post/1729513/


All Articles