Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output HTML in a message in the new Django messages framework?

Tags:

django

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!

like image 223
jsdalton Avatar asked Jan 12 '10 23:01

jsdalton


People also ask

How can I write message in Django?

Adding a message To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.

How do you return a message in Django?

If you leverage the messages framework, you'll still need to add a conditional in the template to display the messages if they exist or not. If I use render() to return a response from a view which is requsted by POST, then if the user refreshes the page the browser will prompt a popup if to send the form again.


2 Answers

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 %} 
like image 69
DavidWinterbottom Avatar answered Oct 23 '22 12:10

DavidWinterbottom


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

like image 36
jphalip Avatar answered Oct 23 '22 12:10

jphalip