2016-12-30 31 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) 

希望它有用..

相关问题