Skip to content
Advertisement

putting a pandas dataframe inside a django template

I want to put a pandas dataframe inside a django template. For instance I want something like this:

<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    THE PANDAS DATAFRAME
  </body>
</html>

What I have tried are these codes. First in my django views.py, this was my function:

from django.shortcuts import render
import pandas as pd

def about(request):
    df = pd.DataFrame({'a': [12, 3, 4], 'b': [5, 6, 7]})
    df = df.to_html(classes='mystyle')
    return render(request, 'blog/about.html', {'table': df})

The template is:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    {{table}}
  </body>
</html>

And, the style.css is:

body {
  background: black;
  color: white;
}

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:

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

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:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    {{table|safe}}
  </body>
</html>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement