0

Django Custom safe excludes from dangerous XSS Injection. Answered from: http://stackoverflow.com/a/41434870/6396981

from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape

register = template.Library()
INVALID_TAGS = ['script', 'style']

def clean_html(value):
    soup = BeautifulSoup(value)
    for tag in soup.findAll(True):
        if tag.name in INVALID_TAGS:
            #tag.hidden = True # you also can hidden it
            tag.replaceWith(escape(tag))
    return soup.renderContents()

@register.filter
def safe_exclude(text):
    """egg: {{ post.description|safe_exclude|safe }}"""  
    return clean_html(text)

This is an example of clean_html.

https://gist.github.com/agusmakmun/b78a713f5387fe4405368239a031d43c

Hope it usefull…

python django tricks solution problem security templates

Your Answer

blog comments powered by Disqus