The Django Template Comment That Ate Our Code Block
A multi-line {# #} comment in a Django template does not comment anything out, and code samples containing braces get parsed as template syntax. Here is what actually happens, and the fix.
We lost most of an afternoon to two Django template behaviours that look unrelated until you hit them on the same page. Both show up when the page you are rendering contains code samples. Both are documented. Both still surprised us, because the failure mode is silent output rather than an exception.
Symptom one: the comment that commented nothing
We wanted to temporarily disable an old hero block in a template while we tried a replacement. Muscle memory from every other language said "wrap it in a comment", so we wrapped it in {# #} and spread it over four lines.
{# old hero, keep for reference
<p>Welcome {{ user.first_name }}</p>
{% if promo %}<p>Promo!</p>{% endif %}
#}
<p>live</p>
What landed in the browser was the greeting we thought we had switched off, with a literal #} floating underneath it. Not an error. Just wrong HTML, quietly.
Diagnosis: render the smallest thing that reproduces it
The temptation here is to reason about it from memory. We have been wrong often enough about template internals that we now do the boring thing instead: render a string through the engine in a throwaway script and print the result. Django's template engine does not need a project to run - you can configure settings inline.
import django
from django.conf import settings
settings.configure(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': False,
'OPTIONS': {},
}])
django.setup()
from django.template import Template, Context
class User:
first_name = 'Sam'
src = """{# old hero, keep for reference
<p>Welcome {{ user.first_name }}</p>
{% if promo %}<p>Promo!</p>{% endif %}
#}
<p>live</p>"""
print(repr(Template(src).render(Context({'user': User()}))))
That script, run with the project's interpreter, prints exactly this:
'{# old hero, keep for reference\n<p>Welcome Sam</p>\n\n#}\n<p>live</p>'
Read that output carefully, because it says three things at once. The opening {# was printed verbatim. The variable {{ user.first_name }} was resolved: the first name is in the output. The {% if promo %} block was executed, found promo falsy, and rendered the empty string. Nothing was commented out. The comment markers became text and the contents stayed live.
The reason is that the lexer's tag pattern matches {# ... #} only within a single line - there is no DOTALL in play, so a newline ends the candidate match. The same script confirms the single-line form works as expected: {# single line comment #}<p>live</p> renders as '<p>live</p>'.
The multi-line form is a block tag, not a brace-hash:
{% comment %}
<p>Welcome {{ user.first_name }}</p>
{% if promo %}<p>Promo!</p>{% endif %}
{% endcomment %}
<p>live</p>
Rendered through the same harness, that produces a blank line followed by <p>live</p> - the contents genuinely gone, no stray markers. One caveat worth knowing: {% comment %} still has to lex its contents, so it will choke on an unbalanced block tag inside it. It is a comment, not a raw region.
Symptom two: the code sample that got eaten
The second problem is the more expensive one, and it is the reason we are writing this down. We were drafting a post that included a GitHub Actions workflow. The YAML contained this line:
deploy:
host: ${{ secrets.PROD_HOST }}
On the live page it rendered as:
deploy:
host: $
Which is, once you see it, completely correct behaviour. Anything the template engine renders is template source. {{ secrets.PROD_HOST }} is a perfectly good variable expression; secrets is not in the context; Django resolves an unknown variable to the empty string by default. The dollar sign in front of it is not part of the expression, so it survives. The braces and their contents do not.
Confirmed with the same three-line harness - Template('deploy:\n host: ${{ secrets.PROD_HOST }}').render(Context({})) prints deploy: and host: $. No warning, no exception. If you have ever pasted a Vue template, a Jinja snippet, a Handlebars partial or a Terraform interpolation into a Django-rendered page, you have probably shipped a mangled version of it.
The durable fix: do not put article bodies through the engine at all
You can patch this case by case with {% verbatim %}, and we will come to that. But on this site the real fix was structural, and it is the one we would recommend for any content-bearing page in a Django project we build.
Post bodies here live in a database column as raw HTML. The template does one thing with them:
<article class="post-body">{{ post.content_html|safe }}</article>
Because the body arrives as a variable value rather than as template source, it is never lexed. Braces in it are inert. A GitHub Actions snippet, a Vue interpolation and a Django tag can all sit in the same article and none of them is touched. The engine renders the template; the body is data the template emits.
That is a trade, and it is worth being explicit about it. |safe means "this HTML is trusted, do not escape it". The safety of the page now rests entirely on who can write that column. On this site the answer is a single superuser account in the Django admin, ours, so the trust boundary is honest. The moment you let untrusted users write a field you render with |safe, you have handed them stored cross-site scripting. If that is your situation, the answer is not |safe; it is a sanitiser with an allow-list of tags and attributes applied on the way in, or a markup format that never yields raw HTML.
The rule we apply: |safe is acceptable when the set of people who can write the field is the same as the set of people who could deploy new templates anyway. Otherwise it is not.
When you really do need literal braces inside a template
Sometimes the braces have to live in the template file itself - a hard-coded example on a documentation page, say. Django has two tools for that, and both are verified by the same harness.
{% verbatim %} turns off the lexer for a region:
{% verbatim %}deploy:
host: ${{ secrets.PROD_HOST }}{% endverbatim %}
That renders as deploy: / host: ${{ secrets.PROD_HOST }} - the braces intact. You can also name the block, {% verbatim myblock %} ... {% endverbatim myblock %}, which lets you nest a literal {% endverbatim %} inside it. That is the escape hatch for writing about {% verbatim %} itself.
For a single stray brace pair, {% templatetag %} emits one delimiter at a time:
{% templatetag openvariable %} user.name {% templatetag closevariable %}
Which renders as {{ user.name }}. It accepts openblock, closeblock, openvariable, closevariable, opencomment, closecomment and openbrace/closebrace. It is verbose, but for one inline example inside otherwise-live markup it beats wrapping a whole region.
Pitfalls we would flag in review
- A missing variable is silent by default. That is what turned symptom two into a rendering bug rather than an error. If you want the noise, set
string_if_invalidinOPTIONSto something loud during development - but not in production, where it will leak into real output. {# #}inside a tag argument is not a comment either. The lexer matches whole tags; a hash inside a quoted string is just a character.- Don't reach for
{% comment %}as a "disable this" switch. Deleting the block and trusting version control is cleaner, and it cannot be lexed at all. - Escaping in stored HTML is your job. If bodies are stored raw and rendered with
|safe, then a<inside a code sample must already be<in the stored text, or it becomes live markup. We check that at import time rather than trusting ourselves at write time.
When not to do this
Storing raw HTML and rendering it with |safe is the wrong call in three situations. If anyone other than a trusted operator can edit the field, you need sanitisation, not trust. If your content is authored by non-technical people who would benefit from Markdown, render Markdown to HTML on save and you get the same "never lexed" property with a friendlier input format. And if the content genuinely needs template features - a per-user greeting inside an article body, say - then you want a deliberately restricted rendering path with a narrow context, not a general one; giving article text full template powers is an injection surface dressed up as a feature.
For a one-off page with two literal braces on it, {% verbatim %} is the proportionate answer and a database column is over-engineering. The structural fix earns its keep when code samples are a recurring part of what the site publishes.
A lot of Django and Python work is exactly this shape: a behaviour that is documented, correct, and still costs somebody an afternoon because the failure is silent. If you have a Django codebase with a bug like that in it, or a build that needs a second pair of eyes, we take on Django and Python work, and the full list of services covers where else we can help. Start a project, tell us what it does and what you expected, and we reply within two business days.
We ship and run our own products. We build yours the same way.
Start a project