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

怎甘沉沦 提交于 2019-12-21 03:35:36

问题


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.


回答1:


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 %}



回答2:


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)))



回答3:


From https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.html.format_html, another option would be to use format_html which will apply escaping to (unsafe) arguments, similar to the escaping in the Template system.

from django.utils.html import format_html

messages.info(request, format_html("My {} <a href='/url'>{}</a>", some_text, other_text))


来源:https://stackoverflow.com/questions/5614203/put-a-a-hyperlink-in-a-django-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!