问题描述
在Django模板中,可以像这样调用一个对象方法:
Inside a Django template, one can call an object method like this :
{{ my_object.my_method }}
问题是当您在def my_method(self)中收到异常/错误时,会隐藏渲染模板(有一个空字符串输出,所以没有错误出现)。
The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).
由于我想调试'def my_method(self)'中有什么问题,我想打开一个像全局django标志这样的异常。
As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.
在settings.py中,我已经有
in settings.py, I already have
DEBUG = True
TEMPLATE_DEBUG = True
我可以收到很多种模板异常,但是当我触发一个对象方法。
I can receive many kind of template exceptions, but none when I trig an object method.
我可以做什么?
推荐答案
一个很好的技巧,我刚刚实现这样做。将它放在您的调试设置中:
Here's a nice trick I just implemented for doing exactly this. Put this in your debug settings:
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")
当分析发现未知或无效的值时,这将导致引发TemplateSyntaxError。我已经测试了一点(具有未定义的变量名称),它的工作原理很好。我没有使用函数返回值进行测试等等。事情可能会变得复杂。
This will cause a TemplateSyntaxError to be raised when the parses sees an unknown or invalid value. I've tested this a little (with undefined variable names) and it works great. I haven't tested with function return values, etc. Things could get complicated.
这篇关于如何看到异常生成到django模板变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!