[Answered ]-How to tell if there's a render error when manually rendering a Django template?

1👍

✅

Sadly enough hacking around the problem like that is the best solution available. It should be noted that the variable is called TEMPLATE_STRING_IF_INVALID btw.

Alternatively I would recommend using Jinja2 together with Coffin, that makes debugging a lot easier as well and Jinja2 actually does give proper stacktraces for errors like these.

1👍

Perhaps you could write the templates in Jinja2 instead. It’s a bit more powerful than Django’s templating language, but can throw exceptions on non-existent variables – and the syntax is very similar.

It also provides similar render etc functions to do just what you’re asking, without affecting any of the rest of your Django project.

For example:

>>> from jinja2 import Environment, StrictUndefined
>>> env = Environment(undefined=StrictUndefined)
>>> template = env.from_string('Say hello to {{name}}')
>>> 
>>> template.render()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 969, in render
     return self.environment.handle_exception(exc_info, True)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
     reraise(exc_type, exc_value, tb)
  File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: 'name' is undefined
>>>
>>> template.render({'name': 'Ben'})
u'Say hello to Ben'
>>>
>>> template.render(name='Ben')
u'Say hello to Ben'

Leave a comment