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

Trying to crash the horse.

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.

Fin

May your templates crash only on purpose,

—Adam


Check out my new book Boost Your GitHub DX.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: