Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see exception generated into django template variable?

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 in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

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.

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.

What can I do ?

like image 772
Eric Avatar asked Nov 29 '10 16:11

Eric


1 Answers

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.

like image 62
slacy Avatar answered Oct 15 '22 07:10

slacy