Show undefined variable errors in Django templates?

后端 未结 8 901
长情又很酷
长情又很酷 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:10

    Finding template variables that didn't exist in the context was important to me as several times bugs made it into production because views had changed but templates had not.

    I used this technique, implemented in manage.py, to achieve the effect of breaking tests when template variables not found in the context were used. Note that this technique works with for loops and if statements and not just {{ variables }}.

    import sys
    
    # sometimes it's OK if a variable is undefined:
    allowed_undefined_variables = [
        'variable_1',
        'variable_2',
    ]
    
    if 'test' in sys.argv:
        import django.template.base as template_base
    
        old_resolve = template_base.Variable.resolve
    
        def new_resolve(self, context):
            try:
                value = old_resolve(self, context)
            except template_base.VariableDoesNotExist as e:
                # if it's not a variable that's allowed to not exist then raise a
                # base Exception so Nodes can't catch it (which will make the test
                # fail)
                if self.var not in allowed_undefined_variables:
                    raise Exception(e)
    
                # re-raise the original and let the individual Nodes deal with it
                # however they'd like
                raise e
    
            return value
    
        template_base.Variable.resolve = new_resolve
    

提交回复
热议问题