GeorgeLPerkins
GeorgeLPerkins

Reputation: 1146

In a Django view, how do I correctly render a returned HTML table to a template?

I'm having trouble correctly passing a html table created with Pandas DataFrame.to_html to a Django view.
How do I do this correctly?

In views.py I have the function:

def my_view(request):
    data_table = Class().main()
    return render_to_response('app/insight.html', {'data_table':data_table})

Class().main() successfully returns a HTML table.

A simplified insight.html body would be:

<body>
    {{data_table}}
</body>

The problem is that I'm getting source like:

&lt;table border=&quot;1&quot; class=&quot;dataframe&quot;&gt;
  &lt;thead&gt;
    &lt;tr style=&quot;text-align: right;&quot;&gt;
      &lt;th&gt;header 1:&lt;/th&gt;
      &lt;th&gt;header 2&lt;/th&gt;
      &lt;th&gt;header 3&lt;/th&gt;
      &lt;th&gt;header 4&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;data 1&lt;/td&gt;
      &lt;td&gt;data 2&lt;/td&gt;
      &lt;td&gt;data 3&lt;/td&gt;
      &lt;td&gt;data 4&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

And a page display of:

<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> </thead> <tbody> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </tbody> </table>

Upvotes: 1

Views: 362

Answers (1)

matyas
matyas

Reputation: 2796

you need to tell the template that it is safe to render html within a variable like this:

<body>
    {{data_table|safe}}
</body>

related answer:https://stackoverflow.com/a/4848661/2174832

Upvotes: 2

Related Questions