开发者

"escaping" variable before passing it to template in Django

开发者 https://www.devze.com 2023-02-26 06:43 出处:网络
I need to pass HTML code to messages and am doing so using templates. In order to get the HTML to work, I mark the message as safe in my template:

I need to pass HTML code to messages and am doing so using templates.

In order to get the HTML to work, I mark the message as safe in my template:

{{ message|safe }}

However, this leaves me open to attack as I'm displaying user generated content in the message. For example:

messag开发者_开发问答es.success(request, "Awesome! \"%s\" is now active." % user_toy)

If user_toy is generated by the user, HTML will go unescaped. How do I fix this?


I was able to fix this using escape from django.utils.html:

from django.utils.html import escape

messages.success(request, "Awesome! \"%s\" is now active." % escape(user_toy))

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号