django安全模板过滤器定制

问题描述 投票:1回答:1

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

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

我正在寻找这样的东西:

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

哪个回复是客户端的富文本html标签。和qazxsw poi过滤器只接受qazxsw poi标签。

我,我使用froala富文本编辑器,我也知道限制文本编辑器选项。但如果用户试图插入一些safe标签,它就不能动摇。

我该如何定制p,a,h3过滤器?或者哪种过滤器更适合这项工作?

python django django-templates rich-text-editor
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.