liveBook · Manning

SafeString

As explained in Django in Action

SafeString is a Django string subclass whose contents are marked as safe from automatic HTML escaping.

SafeString is a Django subclass of Python str whose contents bypass automatic HTML escaping during template rendering. It lets intended markup appear as markup instead of turning characters such as < and > into entities. section 3.7

Use SafeString with care:

  • Call mark_safe() when a complete string already contains trusted HTML. section 3.7
  • Use format_html() to build HTML around values; it returns a SafeString and avoids composing separate marked fragments. section 3.7
  • Remember that operations on a SafeString produce ordinary str objects; mark the result safe again only when appropriate. section 3.7
  • Do not disable escaping for untrusted user input, because malicious content can damage rendered pages. section 3.7

Rendering trusted instrument markup

mark_safe("drum<br/>") renders the line break as HTML. format_html("big <i>{}</i>", "bass") renders an italicized bass name while producing a SafeString for the template.

How Django in Action covers it

How deep it goes
Defines the string subclass and demonstrates mark_safe(), format_html(), rendering, type behavior, and security cautions.
Examples
Demonstrates drum<br/> with mark_safe() and big <i>bass</i> with format_html() in the Django REPL.
What you can do after
Apply it via mark_safe() or format_html() to render trusted HTML while recognizing when escaping protects user input.
How it connects
Connects Django templates with auto-escaping, HTML escaping, mark_safe(), format_html(), and user-input security.

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.