我听说过过滤器|safe
,但如果我理解正确的话,那是不安全的,并且会创建一个用于注入(inject)的后门。
显示带有格式化文本的完整帖子的替代方法是什么?
最佳答案
我想当你不使用 |safe
的过滤器时,那么输出应仅以带有 html 标记的文本形式返回(不呈现为 html 输出)。
但是,如果您需要排除一些危险标签,例如 <script>location.reload()</script>
,您需要使用自定义 templatetag 过滤器来处理它..
我得到了很好的答案:https://stackoverflow.com/a/699483/6396981 ,通过BeautifulSoup
.
from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape
register = template.Library()
INVALID_TAGS = ['script',]
def clean_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name in INVALID_TAGS:
# tag.hidden = True # you also can use this.
tag.replaceWith(escape(tag))
return soup.renderContents()
# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>')
# output:
# <html><body><h1>This is heading</h1> and this one is xss injection <script>location.reload()</script></body></html>
@register.filter
def safe_exclude(text):
# eg: {{ post.description|safe_exclude|safe }}
return clean_html(text)
希望有用..
关于python - 如何用 HTML 标记显示文本? (我使用ckeditor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399271/