Show undefined variable errors in Django templates?

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

    How to log a warning on undefined variable in a template

    It seems that Django relies on undefined variables being a simple empty string. So instead of changing this behaviour or making it throw an exception, let's keep it the same but have it log a warning instead!

    In your settings.py file:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            # ...
            'OPTIONS': {
                # ...
                'string_if_invalid': InvalidStringShowWarning("%s"),
            },
        }
    ]
    

    (string_if_invalid replaces TEMPLATE_STRING_IF_INVALID in newer Django versions.)

    And further up, you'll need to define the InvalidStringShowWarning class, making it behave while logging a warning:

    class InvalidStringShowWarning(str):
        def __mod__(self, other):
            import logging
            logger = logging.getLogger(__name__)
            logger.warning("In template, undefined variable or unknown value for: '%s'" % (other,))
            return ""
    

    You should be able to see the warning in the output of python manage.py runserver.

提交回复
热议问题