diff options
| author | Hasan Ramezani <hasan.r67@gmail.com> | 2019-11-17 20:34:48 +0100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2019-11-27 12:48:07 +0100 |
| commit | 8d322902799019908ec0ded3f08cc8c09425ee8e (patch) | |
| tree | 85d93fccfd688f9e329b7be13e099e8d58d69714 /django | |
| parent | 1f817daa20110987bf155fc6c942a8a14720a66b (diff) | |
Fixed #30425 -- Handled jinja2.TemplateSyntaxError when rendering a template.
Jinja raises jinja2.TemplateSyntaxError in render() not in
get_template() when it's in an included template.
Diffstat (limited to 'django')
| -rw-r--r-- | django/template/backends/jinja2.py | 31 |
1 files changed, 24 insertions, 7 deletions
diff --git a/django/template/backends/jinja2.py b/django/template/backends/jinja2.py index ac7c05895c..d1e5217b51 100644 --- a/django/template/backends/jinja2.py +++ b/django/template/backends/jinja2.py @@ -1,3 +1,5 @@ +from pathlib import Path + import jinja2 from django.conf import settings @@ -68,7 +70,12 @@ class Template: context['csrf_token'] = csrf_token_lazy(request) for context_processor in self.backend.template_context_processors: context.update(context_processor(request)) - return self.template.render(context) + try: + return self.template.render(context) + except jinja2.TemplateSyntaxError as exc: + new = TemplateSyntaxError(exc.args) + new.template_debug = get_exception_info(exc) + raise new from exc class Origin: @@ -88,12 +95,22 @@ def get_exception_info(exception): """ context_lines = 10 lineno = exception.lineno - lines = list(enumerate(exception.source.strip().split("\n"), start=1)) - during = lines[lineno - 1][1] - total = len(lines) - top = max(0, lineno - context_lines - 1) - bottom = min(total, lineno + context_lines) - + source = exception.source + if source is None: + exception_file = Path(exception.filename) + if exception_file.exists(): + with open(exception_file, 'r') as fp: + source = fp.read() + if source is not None: + lines = list(enumerate(source.strip().split('\n'), start=1)) + during = lines[lineno - 1][1] + total = len(lines) + top = max(0, lineno - context_lines - 1) + bottom = min(total, lineno + context_lines) + else: + during = '' + lines = [] + total = top = bottom = 0 return { 'name': exception.filename, 'message': exception.message, |
