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?

maciek
  • 3,198
  • 2
  • 26
  • 33
Paul Biggar
  • 27,579
  • 21
  • 99
  • 152

3 Answers3

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.

maciek
  • 3,198
  • 2
  • 26
  • 33
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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Ignacio, with the new versions of Django, is that still the only way to go? Thanks – glarrain May 04 '12 at 14:51
  • 3
    `django.template` logger was intoduced in Django 1.9 https://docs.djangoproject.com/ja/1.9/topics/logging/#django-template – roboslone Jul 20 '16 at 08:32
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()}
    # ...
}]
tomchuk
  • 166
  • 2
  • 3