【问题标题】:How to display text with HTML-markup? (I use ckeditor)如何使用 HTML 标记显示文本? (我使用ckeditor)
【发布时间】:2017-05-14 22:24:50
【问题描述】:

我听说过过滤器|safe,但如果我理解正确的话,那是不安全的,并且会为注入创建一个后门。

用格式化文本显示完整帖子的替代方法是什么?

【问题讨论】:

    标签: python django django-templates django-ckeditor


    【解决方案1】:

    我认为当您不使用|safe 的过滤器时,输出应该只返回带有html 标记的文本(不呈现为html 输出)

    但是,如果你需要排除一些危险的标签比如<script>location.reload()</script>,你需要使用自定义的模板标签过滤器来处理它..

    我得到了很好的答复: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)
    

    希望有用..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多