繁体   English   中英

django安全模板过滤器定制

[英]django safe template filter customization

我正在使用RTF编辑器对用户的评论进行回复。 但是我需要限制用户在文本编辑器中键入的html标签,以避免xss攻击。

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

我正在寻找这样的事情:

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

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

我使用froala富文本编辑器,我也知道限制文本编辑器选项。 但是,如果用户尝试插入一些<script>标记,则无法理解。

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

您应该为此编写自定义过滤器

您可以安装和使用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'}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM