Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display rows of csv file in django?

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

like image 906
user2237511 Avatar asked May 22 '17 23:05

user2237511


People also ask

Can I use CSV as database in Django?

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.

How import and read CSV file in Django?

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.


1 Answers

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.

like image 154
Timo Avatar answered Oct 09 '22 18:10

Timo