2016-12-30 1 views

ответ

0

Я думаю, что если вы не используете фильтр |safe, тогда вывод должен возвращаться как текст только с разметкой html (не отображается как вывод html).

Но, если вам необходимо исключить некоторые опасных тегов, такие как <script>location.reload()</script>, вам нужно справиться с настраиваемой templatetag фильтром ..

Я получил хороший ответ от: https://stackoverflow.com/a/699483/6396981 через 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) 

Надеется, что это ПОЛЕЗНЫЙ ..

Смежные вопросы