How to see exception generated into django template variable?

前端 未结 6 2063
庸人自扰
庸人自扰 2020-12-29 07:22

Inside a Django template, one can call an object method like this :

{{ my_object.my_method }}

The problem is when you get an exception/bug

6条回答
  •  庸人自扰
    2020-12-29 08:02

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

    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.

提交回复
热议问题