How to get the file name and line number of a Django template error when calling render ()?

I use the Django template system in a standalone tool (not in a web application), for example:

from django import template try: tmpl = loader.get_template(my_template_path) context = template.Context(my_template_context) txt = tmpl.render(context) except (template.TemplateSyntaxError, template.TemplateDoesNotExist), e: # ... 

When the template contains an error, an exception is thrown. How to get file name, line number and error line position? Should I expect to get this information from an exception in this case (not rendering a response for the browser)?

I noticed that TemplateSyntaxError has a source attribute whose value is a tuple containing LoaderOrigin and a pair of numbers. LoaderOrigin has name equal to the file name. The numbers do not seem to resemble the positions of the error symbol, but perhaps there is another way to interpret them?

TemplateDoesNotExist does not have source , only args and message , which provide the name of the template that cannot be found. Is there a way to find the template tag that is loading, or does this error occur at a later stage when line numbers are no longer available?

I really have django.settings , and TEMPLATE_DEBUG is True , if that matters. (I believe this is necessary to get line numbers when rendering templates on web pages displaying fancy errors.) I also use the trivial template loader installed via TEMPLATE_LOADERS , although I don't think it should matter. Also, I am stuck with Django 1.3 at the moment, so a 1.3 compatible solution would be preferable.

Thanks!

+4
source share
1 answer

I believe that the source TemplateSyntaxError attribute is what you are looking for. The Django code means that the numbers indicated are the line numbers between which the error occurred, see https://github.com/django/django/blob/1.3.7/django/views/debug.py#L153 .

Regarding TemplateDoesNotExist , it seems to be ignored when it results from a template tag, see https://github.com/django/django/blob/1.3.7/django/template/loader.py#L50 .

+1
source

Source: https://habr.com/ru/post/1484935/


All Articles