[django] Rendering a template variable as HTML

I use the 'messages' interface to pass messages to user like this:

request.user.message_set.create(message=message)

I would like to include html in my {{ message }} variable and render it without escaping the markup in the template.

This question is related to django django-templates

The answer is


If you want to do something more complicated with your text you could create your own filter and do some magic before returning the html. With a templatag file looking like this:

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
def do_something(title, content):

    something = '<h1>%s</h1><p>%s</p>' % (title, content)
    return mark_safe(something)

Then you could add this in your template file

<body>
...
    {{ title|do_something:content }}
...
</body>

And this would give you a nice outcome.


Use the autoescape to turn HTML escaping off:

{% autoescape off %}{{ message }}{% endautoescape %}

You can render a template in your code like so:

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

See the Django docs for further information.


The simplest way is to use the safe filter:

{{ message|safe }}

Check out the Django documentation for the safe filter for more information.


No need to use the filter or tag in template. Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.

format_html("<h1>Hello</h1>")

Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html