Django: Fail in templates with {% url '' %}

Previously, I covered using 1/0 to crash Python within minimal typing, useful to quickly answer questions like “does the code even get here?”. Recently, I wanted to do the same in Django templates, to trace if a given template was even being rendered, and under which code paths.
It’s a bit more challenging to deliberately crash Django’s template language, since the whole system is designed to be robust, silencing many kinds of errors. The language is also restricted, so {{ 1/0 }} doesn’t work, as variables cannot contain expressions.
Still, after playing around for a bit, I came up with following two options.
First, there’s a way to run 1/0, using divisibleby:
{{ 1|divisibleby:0 }}
On rendering, this raises a classic ZeroDivisionError:
ZeroDivisionError: integer modulo by zero
That said, divisibleby is a bit long and tricky to type.
Second, my preferred method uses the url tag:
{% url '' %}
The {% url %} looks up URLs by name, so providing it the empty string forces no URL to match, raising a NoReverseMatch error:
NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name.
I don’t think there is a shorter way to crash using only the built-in tags and filters, since most have names longer than {% url %}. If you want to crash often, you could write a custom tag, but I think the above is sufficient for most purposes.
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts:
- Python: Fail in three characters with
1/0 - Django: launch pdb in templates with a custom
{% breakpoint %}tag
Tags: django