Django: logging template errors

做~自己de王妃 提交于 2019-12-30 06:44:32

问题


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?


回答1:


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.




回答2:


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.




回答3:


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()}
    # ...
}]


来源:https://stackoverflow.com/questions/2114887/django-logging-template-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!