Skip to content

Instantly share code, notes, and snippets.

@agusmakmun
Last active January 3, 2017 00:26
Show Gist options
  • Save agusmakmun/b78a713f5387fe4405368239a031d43c to your computer and use it in GitHub Desktop.
Save agusmakmun/b78a713f5387fe4405368239a031d43c to your computer and use it in GitHub Desktop.
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',]
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()
# clean_html('<h1>This is heading</h1> and this xss injection <script>location.reload()</script>')
# <html><body><h1>This is heading</h1> and this xss injection &lt;script&gt;location.reload()&lt;/script&gt;</body></html>
@register.filter
def safe_exclude(text):
# egg: {{ post.description|safe_exclude|safe }}
return clean_html(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment