77

I'm trying to display a bit of html in a message that's being displayed via the new Django messages framework. Specifically, I'm doing this via the ModelAdmin.message_user method, which is just a thin wrapper around messages():

def message_user(self, request, message):
    """
    Send a message to the user. The default implementation
    posts a message using the django.contrib.messages backend.
    """
    messages.info(request, message)

Everything I've tried so far seems to display escaped HTML.

self.message_user(request, "<a href=\"http://www.google.com\">Here's google!</a>")

Doesn't work, nor does:

from django.utils.safestring import mark_safe
...
self.message_user(request, mark_safe("<a href=\"http://www.google.com\">Here's google!</a>"))

The display of the template code in the admin base.html template is pretty straightforward:

    {% if messages %}
    <ul class="messagelist">{% for message in messages %}<li>{{ message }}</li>{% endfor %}</ul>
    {% endif %}

So I'm not exactly sure what I am doing wrong.

Thoughts or guidance greatly appreciated, thanks!

1

8 Answers 8

98

Another option is to use extra_tags keyword arg to indicate that a message is safe. Eg

messages.error(request, 'Here is a <a href="/">link</a>', extra_tags='safe')

then use template logic to use the safe filter

{% for message in messages %}
    <li class="{{ message.tags }}">
    {% if 'safe' in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}
    </li>
{% endfor %}
5
  • 4
    Thanks for the tips. I think this is the simplest, yet unobtrusive and most secure approach mentioned here. You can control which message to mark as safe, instead of blindly applying {{message|safe }} globally.
    – Edwin
    Commented Jun 8, 2012 at 17:35
  • 1
    @Edwin Why? When is it not safe to display a message coming from messages framework?
    – kissgyorgy
    Commented Jul 8, 2013 at 4:46
  • 3
    @Walkman: Not if that message contains any untrusted content. Like anything taken from the request; that'd be a XSS hole. Commented Oct 1, 2013 at 12:00
  • 12
    Be careful if you use extra_tags if you're also using bootstrap. You'll see older recommendations everywhere to use alert-{{ message.tags }}, but this will break if you use extra_tags, since you'd get alert-safe, instead of alert-succes, for example. As a solution, you can use alert-{{ message.level_tag }} instead.
    – Brachamul
    Commented Jul 26, 2015 at 17:19
  • @DavidWinterbottom extra_tags='safe' did not work for me. What am I missing?
    – rtindru
    Commented Jun 14, 2016 at 14:13
31

This worked for me (Django 1.11):

from django.contrib import messages
from django.utils.safestring import mark_safe

messages.info(request, mark_safe('This is link to <a href="http://google.com">http://google.com</a>'))
3
  • 6
    Works for Django version 3.1.4 too
    – PowerAktar
    Commented Jan 3, 2021 at 18:31
  • 3
    Thx! Works for bootstrap_messages too! Commented Sep 29, 2021 at 11:24
  • 2
    This works better than the selected answer as adding to tags disrupts using css Bootstrap classes
    – Brian Risk
    Commented Jan 26, 2023 at 15:34
27

As noted in the following Django ticket, it should work if you use mark_safe() in combination with the SessionStorage backend: https://code.djangoproject.com/ticket/14976#comment:9

4
  • 3
    Thanks! Using plain old mark_safe() worked fine once I added MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' to my settings.py.
    – rescdsk
    Commented May 2, 2012 at 18:45
  • This didn't work for me. I think it fails when I set the message and then return a redirect.
    – Carl G
    Commented Jun 19, 2012 at 22:05
  • Cookie session backend appears to be supported: code.djangoproject.com/ticket/14976#comment:11
    – FlyDanoFly
    Commented May 30, 2014 at 21:39
  • 1
    This answer is correct: string safety is preserved by the built in message storages. The problem is that the example template snippets in the docs (and above) for rendering messages use {{ message }} to show the content. To make it work, you need to use {{ message.message }} instead. {{ message }} on its own will call Message.__str__() which converts it from SafeText to str. This leads to the content being escaped. Commented Sep 13, 2017 at 10:19
17

Have you tried {{ message | safe }}?

In the Django template system template variables are always escaped, unless you specify them as safe with the safe filter. This default makes even the unaware protected against an injection attack.

I'm not sure how that interacts with mark_safe, but perhaps something happened in between that made it unsafe again.

4
  • {{ messages|safe }} does indeed work; however, this is a built-in admin base template, so it's not so simple to edit this (plus I don't necessarily want to mark every message as safe). I'm pretty sure the problem is that this since this is being saved during the request cycle (and displayed on the next) any attempts to mark it as safe are going to be futile.
    – jsdalton
    Commented Jan 12, 2010 at 23:48
  • Question: Can you mark the message safe when you put it in the queue? I haven't looked, but it was the first thing that occurred to me. Commented Jan 13, 2010 at 1:42
  • @Peter - Tried that (via mark_safe in the code example in my question), but no luck. From what I can tell, that's not preserved when the message is actually displayed (on the following request).
    – jsdalton
    Commented Jan 13, 2010 at 13:29
  • 2
    -1. When there's any content from the user, this opens XSS. For example, "The URL 'blaablaa' is invalid", which is not that rare.
    – Olli
    Commented Feb 18, 2014 at 20:10
7

You can use format_html. It applies escaping to all arguments.

For example, if we can link with a 'mymodel' detail using an attribute call 'name':

from django.contrib import messages
from django.utils.html import format_html


message = format_html("{} <a href='{}'>{}</a>",
                      "This is the mymodel", 
                      reverse('myapp:mymodel-detail', args=(mymodel.id,)),
                      mymodel.name)
messages.info(request, message)

This answer is based on https://stackoverflow.com/a/33751717/3816639

2

As Ryan Kaske said here, the correct way is to use {{ message.message }} instead of {{ message }}. e.g.

{% if messages %}
    <ul class="messagelist">
        {% for message in messages %}
            <li>{{ message.message }}</li>
        {% endfor %}
    </ul>
{% endif %}
1
  • This was helpful. Wasted hours investigating this. Thank you.
    – rednafi
    Commented Aug 13, 2021 at 22:59
1

The entire point of the templating system is to deal with strings and data like this.

While every other answer instructs you to mark your built string as safe, I would go one step further and tell you to never use HTML in your code - always use a template instead.

The template system makes sure things are properly escaped so you don't have to worry about it, and it's much harder for the programmer to get into the situation where they're building up an HTML string out of a bunch of ifs, and user data.

app/templates/app/fragments/google_link.html:

<a href="https://www.google.com">Here's Google!</a>

views.py:

from django.template import loader

...

def view(request):
    messages.info(
        request,
        loader.render_to_string(
            'app/fragments/google_link.html',
            {},
            request=request,
        ),
    )
1
  • 1
    Just to mention this is the approach I ended up going with to leverage using template. Thanks!
    – EricC
    Commented May 26, 2021 at 15:13
0

I was looking for a way to use unescaped HTML in an admin listing. Not sure if this applies to the messages framework, but using allow_tags as described here helped me.

http://urlencode.blogspot.com/2009/10/neat-django-admin-tricks-part-1.html

1
  • 1
    This is useful, but not related to this question
    – rescdsk
    Commented May 2, 2012 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.