2012-05-04 144 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

相關問題