简体   繁体   中英

django safe template filter customization

i'm using a rich text editor for users comments reply. but i need to limit html tags which users type in text editor for avoiding xss attacks.

i know that safe template filter is best choice. but as a example i'd just accept some tags like <p>,<a>,<h3> not img,script,... . the problem is that safe filter accepts all of html tags.

i'm looking for some thing like this:

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

which reply is client's richtext html tags. and safe flter just accepts p,a,h3 tags.

i,m using froala rich text editor and also i know to limit text editor options. but if user try to insert some <script> tag it can't undrestand.

how can i customize safe filter? or which filter is more appropriate for this job?

You should write custom filter for this

you can install and use 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

and use like {{user.reply|includeHtmlTags:'p,h3,a'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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