2016-12-30 4 views

Antwort

0

Ich denke, wenn Sie die Filter nicht von |safe verwenden, dann mit HTML-Markup (nicht als HTML-Ausgabe gerendert) als Text zurückgeben Ausgabe sollte nur.

Aber, wenn Sie einige gefährliche Tags wie <script>location.reload()</script> ausschließen müssen, können Sie es mit benutzerdefinierten TemplateTag Filter behandeln müssen ..

Ich habe gute Antwort von: https://stackoverflow.com/a/699483/6396981 über BeautifulSoup.

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 use this. 
      tag.replaceWith(escape(tag)) 
    return soup.renderContents() 

# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>') 
# output: 
# <html><body><h1>This is heading</h1> and this one is xss injection &lt;script&gt;location.reload()&lt;/script&gt;</body></html> 

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

Hoffe, dass es sehr nützlich ..