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

Time:03-06

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:

    <body>
        <div >
            <h1 >Datasets Available</h1><hr>
            <div >
                    Output: {{Dataframe|safe}}
            </div>
        </div>
    </body>

CodePudding user response:

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 >
{% for dataframe in dataframes %}
    Output: {{ dataframe|safe }}
{% endfor %}
</div>
  • Related