问题
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