python - 如何查看生成到 django 模板变量中的异常?

标签 python django django-templates

在 Django 模板中,可以像这样调用对象方法:

{{ my_object.my_method }}

问题是当您在“def my_method(self)”中遇到异常/错误时,它在呈现模板时被隐藏(而是输出空字符串,因此不会出现错误)。

因为我想调试“def my_method(self)”中的错误,所以我想打开类似全局 django 标志的东西来接收此类异常。

在settings.py中,我已经有了

DEBUG = True 
TEMPLATE_DEBUG = True

我可以收到多种模板异常,但当我触发一个对象方法时却没有。

我能做什么?

最佳答案

这是我刚刚实现的一个很好的技巧,就是为了做到这一点。将其放入您的调试设置中:

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"),
        },
    },
]

这将导致在解析看到未知或无效值时引发 TemplateSyntaxError。我已经对此进行了一些测试(使用 undefined variable 名)并且效果很好。我还没有测试函数返回值等。事情可能会变得复杂。

关于python - 如何查看生成到 django 模板变量中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4305948/

相关文章:

python - 如何使用 Python 挂载文件系统?

python - 为什么 "m of A called"在此示例中没有打印两次?

python - 来自seaborn的facetgrid中不同数据帧的两行

python - Safari 不显示我的某些内容

python - Django : I can't add more than one row in a Formset without getting an error

django - Django 是否缓存自定义标签和过滤器?

django 处理 textarea 中的换行符

python - 对于颜色逐渐变化的多个图,显示 matplotlib 颜色条而不是图例

Django UUIDField - 让它更短

django - 如何在 django 中使用 django-taggit 按标签过滤帖子