2012-05-04 143 views
1

这是我的代码片段。为什么render_to_response无法正常工作

soup=BeautifulSoup(html_document) 
tabulka=soup.find("table",width="100%") 
dls=tabulka.findAll("dl",{"class":"resultClassify"}) 
tps=tabulka.findAll("div",{"class":"pageT clearfix"}) 
return render_to_response('result.html',{'search_key':search_key,'turnpages 
':tps,'bookmarks':dls}) 

我检查了DLS,它是一个字典只包含一个HTML标签

<dl>label contents contains some <dd> labels</dl> 

但经过通DLS选择render_to_response到的结果是不正确的。 在result.html相应的模板的代码是:

{% if bookmarks %} 
{% for bookmark in bookmarks %} 
{{bookmark|safe}} 
{% endfor %} 
{% else %} 
<p>No bookmarks found.</p> 
{% endif %} 

输出结果的HTML包含这样一个Python字典格式:

[<dd>some html</dd>,<dd>some html</dd>,<dd>some html</dd>,...] 

这出现在输出HTML。这很奇怪。这是一个renfer_to_response的bug吗?

回答

2

那么,dls是一个包含所有匹配元素的文本的python列表。 render_to_response不知道如何处理列表,所以它只是把它变成一个字符串。如果要插入的所有元素为HTML,试着加入成一个单一的一段文字,就像这样:

DLS =“”。加入(DLS)

注意,这样做要粘贴HTML直播从其他来源到您自己的页面,这可能是不安全的。 (如果其中一个dds包含恶意Javascript,会发生什么情况?您是否信任该HTML的提供者?)

+0

+1提到的安全性方面 – heinrich5991

1

在Django中呈现模板时,您必须使用RequestContext实例。

这样说

return render_to_response('login.html',{'at':at}, context_instance = RequestContext(request)) 

此使用,你需要输入如下:

from django.template import RequestContext 

希望这对你的作品。 :)

+0

而不是与RequestContext使用render_to_response您应该导入[渲染](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#django。 ),并使用'return render(request,'result.html',{'search_key':search_key,'turnpages ':tps,'bookmarks':dls})''。渲染是render_to_response,但带有RequestContext。 – olofom

相关问题