tags:

views:

248

answers:

2

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\"&gt;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\"&gt;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!

+4  A: 

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.

Danny Roberts
{{ 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
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.
Peter Rowell
@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
A: 

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

Larry