当Django在呈现模板时遇到未定义的变量错误时,我如何要求Django告诉我?
我已经尝试过明显的DEBUG = True
和TEMPLATE_DEBUG = True
,但它们没有帮助。
发布于 2011-10-22 03:35:06
将其放入您的调试设置中:
class InvalidString(str):
def __mod__(self, other):
from django.template.base import TemplateSyntaxError
raise TemplateSyntaxError(
"Undefined variable or unknown value for: \"%s\"" % other)
TEMPLATE_STRING_IF_INVALID = InvalidString("%s")
当模板引擎看到或发现未定义的值时,这应该会引发错误。
发布于 2015-12-16 22:55:39
如何在模板中记录未定义变量的警告
Django似乎依赖于未定义的变量是一个简单的空字符串。因此,与其改变这种行为或让它抛出异常,不如让它保持不变,但让它记录一个警告!
在settings.py
文件中:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# ...
'OPTIONS': {
# ...
'string_if_invalid': InvalidStringShowWarning("%s"),
},
}
]
(在较新的Django版本中,string_if_invalid
取代了TEMPLATE_STRING_IF_INVALID
。)
接下来,您需要定义InvalidStringShowWarning
类,使其在记录警告时表现出来:
class InvalidStringShowWarning(str):
def __mod__(self, other):
import logging
logger = logging.getLogger(__name__)
logger.warning("In template, undefined variable or unknown value for: '%s'" % (other,))
return ""
def __bool__(self): # if using Python 2, use __nonzero__ instead
# make the template tag `default` use its fallback value
return False
您应该能够在python manage.py runserver
的输出中看到警告。
发布于 2016-07-07 02:16:18
找到上下文中不存在的模板变量对我来说很重要,因为有几次but使其进入生产环境,因为视图发生了变化,但模板没有变化。
我使用了这项在manage.py
中实现的技术,以实现在使用上下文中找不到的模板变量时中断测试的效果。请注意,该技术适用于for
循环和if
语句,而不仅仅是{{ variables }}
。
import sys
# sometimes it's OK if a variable is undefined:
allowed_undefined_variables = [
'variable_1',
'variable_2',
]
if 'test' in sys.argv:
import django.template.base as template_base
old_resolve = template_base.Variable.resolve
def new_resolve(self, context):
try:
value = old_resolve(self, context)
except template_base.VariableDoesNotExist as e:
# if it's not a variable that's allowed to not exist then raise a
# base Exception so Nodes can't catch it (which will make the test
# fail)
if self.var not in allowed_undefined_variables:
raise Exception(e)
# re-raise the original and let the individual Nodes deal with it
# however they'd like
raise e
return value
template_base.Variable.resolve = new_resolve
https://stackoverflow.com/questions/4300442
复制相似问题