CodeX
Published in

CodeX

How to Easily Transform Any Pandas DataFrame to HTML Tables in Django

A real-world example and custom Django template tag

Photo by Helena Hertz on Unsplash

Custom Template Tags

from django import templateregister = template.Library()def convert_data_frame_to_html_table_headers(df):  html = "<tr>"  for col in df.columns:  html += f"<th>{col}</th>"  html += "</tr>"  return html
def convert_data_frame_to_html_table_rows(df): html = "" for row in df.values: row_html = "<tr>" for value in row: row_html += f"<td>{value}</td>" row_html += "</tr>"
html += row_html
return html
register.filter("convert_data_frame_to_html_table_rows", convert_data_frame_to_html_table_rows)register.filter("convert_data_frame_to_html_table_headers", convert_data_frame_to_html_table_headers)

Using The Tags

{% extends 'partials/base.html' %}{% load static %}# this is the file that I created to store my template tags
{% load datagateway_template_tags %}
<table id="efficiency-hub-table" class="table table-bordered dt-responsive nowrap w-100"> <thead>
{{ table_data | convert_data_frame_to_html_table_headers | safe}}
</thead>
<tbody>
{{table_data | convert_data_frame_to_html_table_rows | safe}}
</tbody>
</table>

Finally

Image by Author

--

--

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Baysan

Lifelong learner & Freelancer. I use technology that helps me. I’m currently working as a Business Intelligence & Backend Developer. mebaysan.com