I’m trying to display a dictionary via html in django app and that each value of dictionary is a dataframe.
I’m able to print key but not dataframe for which I’ve tried many different approaches.
Either I get key value pair printed which is not very human readable or I get Could not parse the remainder error
Here’s snippet of views.py
context = {'rail': rail}
return render(request, 'sample_output.html', context)
where rail is my dictionary
Here’s snippet of html
<table>
<thead>
<tr>
{% for key in rail.keys %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody style="height: 400px; overflow-y: scroll;">
{% for key, value in rail.items %}
<tr>
<td>{{ key }}</td>
<td>
<ul>
{% for index, row in value.iterrows %}
<tr>
{% for cell in row %}
<td>
{% if cell is not pandas.isnull(pandas.NaT) %}
{{ cell }}
{% else %}
NaT
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
>Solution :
Use to_html() with safe filter:
context = {'rail': {k: v.to_html() for k, v in rail.items()}}
For each dataframe, use {{ mydf | safe }}
Example:
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
print(df.to_html())
# Output
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>3</td>
</tr>
<tr>
<th>1</th>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>