Search code examples
pythonhtmldjangowebrender-to-response

Why the render_to_response not working properly


This is a snippet of my code.

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})

I checked the dls, it is a dict contains only one html label

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

But after pass dls to render_to_response the result is not correct. The corresponding template code in result.html is:

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

The output result html contains a python dictionary format like this:

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

This appears in the output html. That is very strange. Is this a bug of renfer_to_response?


Solution

  • Well, dls is a python list containing the text of all the matching elements. render_to_response doesn't know what to do with a list, so it just turns it into a string. If you want to insert all the elements as HTML, try joining them into a single piece of text like so:

    dls = "".join(dls)

    Note that by doing so you are pasting live HTML from some other source into your own page, which is potentially unsafe. (What happens if one of the dds contains malicious Javascript? Do you trust the provider of that HTML?)