django 安全模板过滤器定制

django safe template filter customization

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

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

我正在寻找这样的东西:

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

哪个回复是客户的富文本 html 标签。 safe 过滤器只接受 p,a,h3 个标签。

我正在使用 froala 富文本编辑器,而且我知道要限制文本编辑器选项。但如果用户尝试插入一些 <script> 标签,它就无法理解。

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

你应该为此写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'}}