2013-10-21 136 views
-2

我使用safe过滤器,我想逃避到处于<code></code>标签只有HTML标记,意味着<b>Hello</b>将呈现为你好<code><b>Hello</b></code>将呈现为<b>Hello</b>。所以我写的自定义过滤器,但我得到这个错误:Django的自定义过滤器AttributeError的

Exception Type: AttributeError 
Exception Value:'ResultSet' object has no attribute 'replace' 
Exception Location: G:\python\Python\python practice\python website\firstpage\custom_filters\templatetags\custom_filters.py in code_escape, line 10 

我的代码是:

from bs4 import BeautifulSoup 

from django import template 
register = template.Library() 

@register.filter 
def code_escape(value): 
    soup = BeautifulSoup(value) 
    response = soup.find_all('code') 
    string = response.replace('<', '&lt;') 
    string = string.replace('>', '&gt;') 
    string = string.replace("'", '&#39') 
    string = string.replace('"', '&quot') 
    final_string = string.replace('&', '&amp') 
    return final_string 

template.html

....... 

{% load sanitizer %} 
{% load custom_filters %} 

...... 

{{ content|escape_html|safe|linebreaks|code_escape }} 

....... 
+0

“不工作”,你能解释这是什么意思?如果你有错误,你能把它放在这里吗?你能否提供一些样本数据,以及你想要输出的数据是什么?在这个代码转储中的究竟是我们正在寻找什么? –

+0

我添加了我得到的错误,并输出我想要的。 –

回答

0

find_all返回ResultSet这是迭代。我相信你可以编辑标签的值.string。尝试这样的:

soup = BeautifulSoup(value) 
for code_tag in soup.find_all('code'): 
    code_tag.string = code_tag.string.replace('<', '&lt;') 
    code_tag.string = code_tag.string.replace('>', '&gt;') 
    code_tag.string = code_tag.string.replace("'", '&#39') 
    code_tag.string = code_tag.string.replace('"', '&quot') 
    code_tag.string = code_tag.string.replace('&', '&amp') 
return str(soup) 
+0

'.string'可能不适用于'cod_tag',因为它本身就是字符串。但我得到我的解决方案,并将其作为下面的答案。 感谢您的努力.... –