Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting unset variables in Django templates

As a long time PHP developer, I'm used to the idea of setting the error level for my application to warn me when I am using an uninitialized variable. I was wondering if a similar feature exists in Django, where I can detect at run-time that I am using a variable in my template that was not explicitly passed to the template via the view?

For example, I misspelled a variable name in the template

{{ mysearch }}

When it should've been

{{ my_search }}

Common mistake, not paying attention while typing, etc. In PHP I would've seen a warning about using an uninitiailzed variable but Django doesn't seem to care and just keeps on going like nothing happened. From a debugging perspective, it would be awesome to detect when I've made a mistake like that.

Any thoughts?

like image 494
GrumpyCanuck Avatar asked Jan 21 '10 03:01

GrumpyCanuck


2 Answers

Are you looking for this? http://docs.djangoproject.com/en/1.1/ref/templates/api/#invalid-template-variables

Have you tried setting TEMPLATE_STRING_IF_INVALID? e.g.,

TEMPLATE_STRING_IF_INVALID = 'DEBUG WARNING: template variable [%s] is not defined'

That will cause that string to be printed in the rendered html for each spot where an undefined variable was referenced, along with the variable name.

Read this: http://docs.djangoproject.com/en/1.1/ref/settings/#setting-TEMPLATE_STRING_IF_INVALID

like image 128
S.Lott Avatar answered Oct 21 '22 06:10

S.Lott


In newer versions of Django you can get messages about unset template variables by outputting messages from the 'django.template' logger by modifying the LOGGING setting.

LOGGING = {
    # ... [SNIP]
    'loggers': {
        # ... [SNIP]
        'django.template': {
            'handlers': ['console'],
            'propagate': False,
            'level': 'DEBUG',
        }
    },
}
like image 31
Tim Tisdall Avatar answered Oct 21 '22 05:10

Tim Tisdall