简体   繁体   English

django安全模板过滤器定制

[英]django safe template filter customization

i'm using a rich text editor for users comments reply. 我正在使用RTF编辑器对用户的评论进行回复。 but i need to limit html tags which users type in text editor for avoiding xss attacks. 但是我需要限制用户在文本编辑器中键入的html标签,以避免xss攻击。

i know that safe template filter is best choice. 我知道safe模板过滤器是最佳选择。 but as a example i'd just accept some tags like <p>,<a>,<h3> not img,script,... . 但是作为示例,我只接受<p>,<a>,<h3>类的标签<p>,<a>,<h3>而不是img,script,... the problem is that safe filter accepts all of html tags. 问题是safe过滤器接受所有html标签。

i'm looking for some thing like this: 我正在寻找这样的事情:

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

which reply is client's richtext html tags. 哪个回复是客户的RTF html标签。 and safe flter just accepts p,a,h3 tags. safe过滤器只接受p,a,h3标签。

i,m using froala rich text editor and also i know to limit text editor options. 我使用froala富文本编辑器,我也知道限制文本编辑器选项。 but if user try to insert some <script> tag it can't undrestand. 但是,如果用户尝试插入一些<script>标记,则无法理解。

how can i customize safe filter? 如何自定义safe过滤器? or which filter is more appropriate for this job? 或者哪个过滤器更适合这项工作?

You should write custom filter for this 您应该为此编写自定义过滤器

you can install and use BeautifulSoup 您可以安装和使用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

In your template load {% load includeHtmlTags %} at top 在您的模板加载{% load includeHtmlTags %}顶部

and use like {{user.reply|includeHtmlTags:'p,h3,a'}} 并使用类似{{user.reply|includeHtmlTags:'p,h3,a'}}

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

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