Show undefined variable errors in Django templates?

后端 未结 8 873
长情又很酷
长情又很酷 2020-12-24 08:50

How can I ask Django to tell me when it encounters, for example, an undefined variable error while it\'s rendering templates?

I\'ve tried the obvious DEBUG = T

相关标签:
8条回答
  • 2020-12-24 09:21

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

    This should raise an error when the template engine sees or finds an undefined value.

    0 讨论(0)
  • 2020-12-24 09:31

    I believe that's a major oversight on Django's part and the primary reason I prefer not to use their default template engine. The sad truth is that, at least for now (Django 1.9), you can't achieve this effect reliably.

    • You can make Django raise an exception when {{ undefined_variable }} is encountered - by using "the hack" described in slacy's answer.

    • You can't make Django raise the same exception on {% if undefined_variable %} or {% for x in undefined_variable %} etc. "The hack" doesn't work in such cases.

    • Even in cases in which you can, it is strongly discouraged by Django authors to use this technique in production environment. Unless you're sure you don't use Django's built-in templates in your app, you should use "the hack" only in DEBUG mode.

    However, if you're stuck with Django's templates for now, I would recommend to use slacy's answer, just make sure you're in DEBUG mode.

    0 讨论(0)
提交回复
热议问题