【问题标题】:django safe template filter customizationdjango安全模板过滤器定制
【发布时间】:2019-08-16 16:49:13
【问题描述】:

我正在为用户 cmets 回复使用富文本编辑器。但我需要限制用户在文本编辑器中输入的 html 标签,以避免 xss 攻击。

我知道safe 模板过滤器是最佳选择。 但作为一个例子,我只接受一些标签,比如 <p>,<a>,<h3> 而不是 img,script,... 。问题是safe过滤器接受所有的html标签。

我正在寻找这样的东西:

{{user.reply|safe:'<p>,<h3>,<a>'}}

哪个回复是客户端的富文本 html 标签。 而safe flter 只接受p,a,h3 标签。

我,我使用 froala 富文本编辑器,而且我知道限制文本编辑器选项。但是如果用户尝试插入一些&lt;script&gt; 标签,它就无法理解。

如何自定义safe 过滤器?或者哪个过滤器更适合这项工作?

【问题讨论】:

    标签: python django django-templates rich-text-editor


    【解决方案1】:

    你应该为此写custom filter

    可以安装使用BeautifulSoup

    from bs4 import BeautifulSoup
    from django import template
    
    register = template.Library()
    
    @register.filter(name='includeHtmlTags')
    def includeHtmlTags(value, arg):
        include=arg.split(",")
        soup=BeautifulSoup(text, 'html.parser')
        return_value=''
        for tag in include:
            for i in soup.findAll(tag):
                return_value += i
        return return_value
    

    在您的模板中加载顶部的{% load includeHtmlTags %}

    并像{{user.reply|includeHtmlTags:'p,h3,a'}}一样使用

    【讨论】:

    • 没试过,请您测试看看,如果影响我们可以改进。
    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2013-04-14
    • 2011-04-12
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多