Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a <a> hyperlink in a django message [duplicate]

I'm using django messages and i want to put an hyperlink in it.

view.py:

from django.contrib import messages

def my_view(request):
    messages.info(request,"My message with an <a href='/url'>hyperlink</a>")

Obviously, in my page, i see the html code and no hyperlink. How to treat the message as an htlml code ?

Hope this is clear.

like image 739
Guillaume Thomas Avatar asked Apr 10 '11 19:04

Guillaume Thomas


2 Answers

If you don't want to turn off autoescaping on all messages/templates, you can use mark_safe for that particular message:

from django.utils.safestring import mark_safe

messages.info(request, mark_safe("My message with an <a href='/url'>hyperlink</a>"))

And if you maybe have some unsafe parts of your message, you can use cgi.escape to escape those parts.

from cgi import escape
messages.info(request, mark_safe("%s <a href='/url'>hyperlink</a>" % escape(unsafe_value)))
like image 117
BB. Avatar answered Oct 12 '22 15:10

BB.


Strings in Django templates are automatically escaped. You don't want your raw HTML to be auto-escaped, so you should either pass the string to the safe filter:

{{ message|safe }}

or disable autoescape with the autoescape tag:

{% autoescape off %}
    {{ message }}
{% endautoescape %}
like image 17
mipadi Avatar answered Oct 12 '22 14:10

mipadi