I have a django app, which allows the user to upload a csv file, say a csv file of rankings of universities. I'd have to process the data that has been uploaded. For example, grey out any column which has string values and calculate the mean and std. deviation of all the values of a column. For this, I am using Pandas and converting the csv file to a pandas dataframe.
How do I display the dataset from the csv file using django? The column names cannot be hard coded because the user may upload any csv file. I checked django-tables2 and did the following
csvfile = request.FILES['csv_file']
data = pd.read_csv(csvfile.name)
context = {'loaded_data': data}
return render(request, "dataflow/table.html", context)
but I get the error ValueError: Expected table or queryset, not DataFrame
Django uses python's built-in csv library to create Dynamic CSV (Comma Separated values) file. We can use this library into our project's view file. Lets see an example, here we have a django project to that we are implementing this feature. A view function getfile() is created.
Uploading CSV file: First create HTML form to upload the csv file. Use below code for the same. Important: Do not forget to include enctype="multipart/form-data" in form. Add a URL in URLpatterns.
Pandas dataframe can be converted to html table by itself. You can try
csvfile = request.FILES['csv_file']
data = pd.read_csv(csvfile.name)
data_html = data.to_html()
context = {'loaded_data': data_html}
return render(request, "dataflow/table.html", context)
In the html page, use {{loaded_data | safe}}
to render the table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With