|
21 | 21 | from django.utils.module_loading import import_string |
22 | 22 |
|
23 | 23 | from mako.template import Template as MakoTemplate |
| 24 | +from mako.exceptions import RichTraceback |
24 | 25 | from mako import exceptions as mako_exceptions |
25 | 26 |
|
26 | 27 |
|
@@ -164,7 +165,38 @@ def render(self, context=None, request=None): |
164 | 165 | context['csrf_input'] = csrf_input_lazy(request) |
165 | 166 | context['csrf_token'] = csrf_token_lazy(request) |
166 | 167 |
|
167 | | - return self.template.render(**context) |
| 168 | + try: |
| 169 | + return self.template.render(**context) |
| 170 | + except Exception as e: |
| 171 | + traceback = RichTraceback() |
| 172 | + |
| 173 | + source = traceback.source |
| 174 | + if not source: |
| 175 | + # There's no template source lines then raise |
| 176 | + raise e |
| 177 | + |
| 178 | + source = source.split('\n') |
| 179 | + line = traceback.lineno |
| 180 | + top = max(0, line - 4) |
| 181 | + bottom = min(len(source), line + 5) |
| 182 | + source_lines = [(i + 1, source[i]) for i in range(top, bottom)] |
| 183 | + |
| 184 | + e.template_debug = { |
| 185 | + 'name': traceback.records[5][4], |
| 186 | + 'message': '{}: {}'.format( |
| 187 | + traceback.errorname, traceback.message), |
| 188 | + 'source_lines': source_lines, |
| 189 | + 'line': line, |
| 190 | + 'during': source_lines[line - top - 1][1], |
| 191 | + 'total': bottom - top, |
| 192 | + 'bottom': bottom, |
| 193 | + 'top': top + 1, |
| 194 | + # mako's RichTraceback doesn't return column number |
| 195 | + 'before': '', |
| 196 | + 'after': '', |
| 197 | + } |
| 198 | + |
| 199 | + raise e |
168 | 200 |
|
169 | 201 | @staticmethod |
170 | 202 | def get_reverse_url(): |
|
0 commit comments