0

I have a html file I am passing from my views.py as a context and I can load up a table in my html by simply writing {{loaded_data|safe}}. However, I want to add a bootstrap class to it so that it is formatted nicely. I've looked through the jinja2 documentation and tried

<table class="table">
   {{loaded_data}}
</table>

but none of my attempts worked and I can't seem to find an answer.
Here's a snippet from my views.py

    data = pd.read_csv(csv_file)
    data_html = data.to_html()
    context = {'loaded_data': data_html}

So my question is: How should I go about formatting my table passed as a context from views.py?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
IceTea
  • 598
  • 1
  • 6
  • 19
  • how are you defining `loaded_data`? is it stored as a string? or are you reading another html file? – Aman Garg Apr 18 '19 at 17:31
  • @AmanGarg I've added a snippet from my views.py! I'm reading loaded_data as a html – IceTea Apr 19 '19 at 05:34
  • Since you basically have a html string created from a file, you will have to manipulate it using Python. I suggest you to solve this using [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) – Aman Garg Apr 19 '19 at 05:47
  • @AmanGarg Is there a way to reference html elements directly without using BeautifulSoup? – IceTea Apr 19 '19 at 05:50
  • 1
    checkout this answer: https://stackoverflow.com/a/52644615/4186008 – Aman Garg Apr 19 '19 at 06:10

1 Answers1

1

Pandas let's you do this:

data_html = data.to_html(classes='table')    

see documentation

bhaskarc
  • 9,269
  • 10
  • 65
  • 86
  • Thanks! Great to see when there's a clean fix. Can't believe I didn't think about looking at the pandas documentation, instead I was googling everywhere for a django/html fix – IceTea Apr 19 '19 at 08:08