Problem
You want to embed HTML within a message using Django's messages framework.
This is a reasonably common requirement - for instance, it's common to want to include a link within the message, perhaps pointing the user towards a sign-in or registration page.
This problem exists as of Django 1.4 but may be solved within the framework in later versions.
Solution
Use the extra_tags keyword argument to pass a flag indicating that the message is safe for rendering without escaping. For example:
CODE:
1.from django.contrib import messages
2.
3.def some_view(request):
4....
5.messages.success(request,
6.'Here is a
link.',
7.extra_tags='safe')Then use some simple template logic to determine whether to use the safe filter:
CODE:
01.
02.{% for message in messages %}
03.
04.{% if 'safe' in message.tags %}
05.{{ message|safe }}
06.{% else %}
07.{{ message }}
08.{% endif %}
09.
10.{% endfor %}
11.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/301743/viewspace-734245/
,如需转载,请注明出处,否则将追究法律责任。