liveBook · Manning

Format_html

As explained in Django in Action

format_html is a Django utility that formats arguments into an HTML string and returns a SafeString.

format_html() builds a small HTML fragment with Python-style braces, fills its placeholders, and returns a SafeString. It is a tidy alternative to assembling pieces manually and marking the result safe. section 3.7

Format an instrument name

from django.utils.html import format_html instrument = format_html("big <i>{}</i>", "bass") # Rendered output includes: big <i>bass</i> The HTML tags remain active in the template output, while the placeholder supplies the instrument value. Treat escaping controls carefully when values originate from users. section 3.7

Listing 3.14 Using format_html() to mark data as safe in the Django REPL
>>> from django.utils.html import format_html
>>> instrument = "bass"
>>> instrument = format_html("big <i>{}</i>", instrument)
>>> data = {"instrument":instrument}
>>> t.render(Context(data))
"I love the sound a big <i>bass</i> makes.\n
 A shiny big <i>bass</i> is good.\n\\n\\n
 Don't put a big <i>bass</i> too close to your ear.\n\\n"

Inspect the complete Django REPL example, including the import, formatted value, template context, and rendered output. section 3.7

How Django in Action covers it

How deep it goes
Defines the str.format-style interface, SafeString result, REPL usage, and escaping caution without exploring implementation internals.
Examples
Demonstrates formatting an italicized bass label and rendering it through a Django template in the REPL.
What it assumes
Assumes basic Python string formatting and Django template rendering; demonstrates the safety distinction from zero.
What you can do after
Apply it via Django’s format_html() utility to construct concise HTML fragments and render them as safe strings.
How it connects
Connects HTML auto-escaping with SafeString, mark_safe(), and Python’s str.format() behavior.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.