python - 如何用 HTML 标记显示文本? (我使用ckeditor)

标签 python django django-templates django-ckeditor

我听说过过滤器|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 &lt;script&gt;location.reload()&lt;/script&gt;</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/

相关文章:

django - 如何更改第三方 Django 应用程序的字段或模型属性?

Django-taggit:如何检索由某种类型的帖子过滤的所有标签

python - 我无法在模板中加载静态文件。我究竟做错了什么?

python - 更改默认 float 的重要数字报告

django - 根据 Django 应用程序中的 Drupal 用户数据库表进行身份验证

django - 什么是 Django 模板系统中 Jinja 宏的适当等价物?

django - 如何检索模板变量中的前 10 个元素?

python - 访问 MIB 对象

python - Set_column 在手动激活每个单元格之前不起作用

python - 监视从 Windows 中的 shell 命令创建的子进程