I want to put a pandas dataframe inside a django template. For instance I want something like this:
JavaScript
x
7
1
<html>
2
<head><title>HTML Pandas Dataframe with CSS</title></head>
3
<body>
4
THE PANDAS DATAFRAME
5
</body>
6
</html>
7
What I have tried are these codes. First in my django views.py, this was my function:
JavaScript
1
8
1
from django.shortcuts import render
2
import pandas as pd
3
4
def about(request):
5
df = pd.DataFrame({'a': [12, 3, 4], 'b': [5, 6, 7]})
6
df = df.to_html(classes='mystyle')
7
return render(request, 'blog/about.html', {'table': df})
8
The template is:
JavaScript
1
9
1
{% load static %}
2
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
3
<html>
4
<head><title>HTML Pandas Dataframe with CSS</title></head>
5
<body>
6
{{table}}
7
</body>
8
</html>
9
And, the style.css is:
JavaScript
1
5
1
body {
2
background: black;
3
color: white;
4
}
5
Apparently, when I check it in my browser the template is loaded with the CSS code correctly but it gives me the following output instead of the table that I want:
JavaScript
1
2
1
<table border="1" class="dataframe mystyle"> <thead> <tr style="text-align: right;"> <th></th> <th>a</th> <th>b</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>12</td> <td>5</td> </tr> <tr> <th>1</th> <td>3</td> <td>6</td> </tr> <tr> <th>2</th> <td>4</td> <td>7</td> </tr> </tbody> </table>
2
I am new to django, so maybe my approach is completely wrong.
Advertisement
Answer
I found the solution by myself. Apparently I should change {table}
to {table|safe}
in the template file. So, the code looks like this:
JavaScript
1
9
1
{% load static %}
2
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
3
<html>
4
<head><title>HTML Pandas Dataframe with CSS</title></head>
5
<body>
6
{{table|safe}}
7
</body>
8
</html>
9