Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to render a data frame from views.py to an html template in django?

I’m building a webapp with Django, and one of the features is that the user can upload a dataset and view it on another page. I’m currently only attempting to read a dataset from a file path and display it in another page; I’ve placed my test.csv in the file that I want to read from, but I keep getting the error ‘list’ object has no attribute ‘to html’.

Here is the views.py:

    path = r"C:/Users/user/Documents/django_saved_files/"
    
    path1, dirs, files = next(os.walk(path))
    file_count = len(files)
    dataframes_list = []
    for i in range(file_count):
        temp_df = pd.read_csv(path+files[i])
        dataframes_list.append(temp_df)

    dataframes_list_html = dataframes_list.to_html(index=False)

    return render(request,'blog/view_datasets.html',{'Dataframe':dataframes_list_html})

and Here is the HTML Template:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <body>
        <div class="container">
            <h1 class="section-header">Datasets Available</h1><hr>
            <div class="content-section">
                    Output: {{Dataframe|safe}}
            </div>
        </div>
    </body>

>Solution :

Create a list of HTML data instead of the dataframes with:

dataframes_list_html = []
for i in range(file_count):
    temp_df = pd.read_csv(path+files[i])
    dataframes_list_html.append(temp_df.to_html(index=False))
return render(request,'blog/view_datasets.html',{'dataframes': dataframes_list_html})

and then enumerate over the list in the template and render the dataframes:

<div class="content-section">
{% for dataframe in dataframes %}
    Output: {{ dataframe|safe }}
{% endfor %}
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading