Eri*_*ric 16 python django django-templates
在Django模板中,可以调用这样的对象方法:
{{ my_object.my_method }}
Run Code Online (Sandbox Code Playgroud)
问题是当你在'def my_method(self)'中遇到异常/错误时,它在渲染模板时被隐藏(相反,有一个空字符串输出,因此不会出现错误).
因为我想调试'def my_method(self)'中的错误,我想打开类似全局django标志的东西来接收这样的异常.
在settings.py中,我已经有了
DEBUG = True
TEMPLATE_DEBUG = True
Run Code Online (Sandbox Code Playgroud)
我可以接收多种模板异常,但是当我触发对象方法时没有.
我能做什么 ?
sla*_*acy 14
这是我刚刚实现的一个很好的技巧.把它放在你的调试设置中:
class InvalidString(str):
def __mod__(self, other):
from django.template.base import TemplateSyntaxError
raise TemplateSyntaxError(
"Undefined variable or unknown value for: %s" % other)
// this option is deprecated since django 1.8
TEMPLATE_STRING_IF_INVALID = InvalidString("%s")
// put it in template's options instead
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
// ...
'OPTIONS': {
'string_if_invalid': InvalidString("%s"),
},
},
]
Run Code Online (Sandbox Code Playgroud)
当分析看到未知或无效值时,这将导致引发TemplateSyntaxError.我已经对此进行了一些测试(使用未定义的变量名称)并且效果很好.我没有测试函数返回值等.事情可能会变得复杂.
我能做些什么 ?
评估视图函数中的异常生成方法。
def someView( request ):
.... all the normal work ...
my_object.my_method() # Just here for debugging.
return render_to_response( ... all the normal stuff... )
Run Code Online (Sandbox Code Playgroud)
完成调试后,您可以删除该行代码。