Django: logging template errors
Asked Answered
P

3

5

When I make an error in a django template {{placeholder}}, I get no error, just blank space in the output where I was expecting content. Is there a way to see something in my logs when this occurs, preferably using logging.warning or logging.error?

Portauprince answered 22/1, 2010 at 4:11 Comment(0)
Y
2

The only thing Django provides for handling unknown context variables in TEMPLATE_STRING_IF_INVALID. You're going to have to do some deeper hacking of the template engine if you want better than that.

Yoshikoyoshio answered 22/1, 2010 at 4:48 Comment(2)
Ignacio, with the new versions of Django, is that still the only way to go? ThanksDelectate
django.template logger was intoduced in Django 1.9 docs.djangoproject.com/ja/1.9/topics/logging/#django-templateFrugivorous
B
7

Yes, there is. Just add in your development 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'),
        },
    },
}

As roboslone stated, Django 1.9 did introduce it. The snippet is very similar to the second of Configuring logging examples in Django docs.

Biogen answered 8/12, 2017 at 22:9 Comment(0)
Y
2

The only thing Django provides for handling unknown context variables in TEMPLATE_STRING_IF_INVALID. You're going to have to do some deeper hacking of the template engine if you want better than that.

Yoshikoyoshio answered 22/1, 2010 at 4:48 Comment(2)
Ignacio, with the new versions of Django, is that still the only way to go? ThanksDelectate
django.template logger was intoduced in Django 1.9 docs.djangoproject.com/ja/1.9/topics/logging/#django-templateFrugivorous
F
0

In Django >= 1.8, TEMPLATE_STRING_IF_INVALID has been deprecated in favor of string_if_invalid in settings.TEMPLATES.

If you want to do a little more than depend on DEBUG messages from the django.template logger, you can fool the following code in 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_invalid in settings.TEMPLATES:

TEMPLATES = [{
    'OPTIONS': {'string_if_invalid': InvalidString()}
    # ...
}]
Frangible answered 6/3, 2017 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.