sending html to django template from view

半世苍凉 提交于 2021-02-11 17:58:20

问题


I am new to django so I may be going about this the wrong way (pretty sure I am).

Trying to get a webpage to display data from a postgresql DB in a table showing a status for a list of servers.

This is part of the template

<div class"row"=""><div class="span3" style="background-color:lightyellow; margin-left:20px">
<table class="table table-bordered table-condensed">
        <thead>
          <tr>
            <th>Server</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
        {{ res }}
        </tbody>
      </table>
</div></div>

In my view I have this,

message = []
for res in data:
    message.append("          <tr>")
    message.append("            <td>" + str(res).split("'")[1] + "</td>")
    if str(res).split("'")[3] == 'No':
        message.append("            <td><FONT COLOR=\"008200\">Available</FONT> </td>")
    else:
        message.append("            <td><FONT COLOR=\"FF0000\">Down</FONT> </td>")
    message.append("          </tr>")

return render_to_response('health.html', {'res':message}, context_instance=RequestContext(request))

If I print that instead of doing the append I get the resulting HTML I would expect.

As it currently is, I don't get anything displayed on the webpage in that table.

I don't expect it to render the list necessarily, but would have thought something should have showed up in the table even if it was incorrect format.

Should this HTML processing be done in the template and not the view?


回答1:


Yes, it is usually best to do all HTML processing in the template. This way you can separate your database access logic from your display logic and thereby reduce coupling. It also means you can easily re use template.

So you should use the view function to get the appropriate objects and pass them to the template as variables.

Still, you are sort of on the right track. In order for your {{res}} variable to display properly I think you will need to change the template to.

<tbody>
    {% for message in res %}
    {{ message }}
    {% endfor %}
</tbody>

This should iterate over the elements in the res variable which you passed to the template.



来源:https://stackoverflow.com/questions/15016316/sending-html-to-django-template-from-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!