模板变量中的异常

模板变量中的异常

本文介绍了如何查看生成到 django 模板变量中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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)

// 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.我已经对此进行了一些测试(使用未定义的变量名称)并且效果很好.我还没有测试过函数返回值等.事情可能会变得复杂.

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 模板变量中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:28