Django 1.5 How to read csv from memory

I am trying to figure out how to read a downloaded CSV without saving it to disk ...

I am stuck in form.cleaned_data ['file']. read ... I seem to be getting nothing

If I can only figure out how to get the output, then I can write the appropriate function to process the data rows.

#addreport.html <form enctype="multipart/form-data" method="post" action="/products/addreport/"> {%csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> 

 #forms.py from django import forms # class UploadFileForm(forms.Form): file = forms.FileField() 

-

 # views.py def addreport(request): if request and request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print form.cleaned_data['file'].read() else: print form.errors print request.FILES #form = UploadFileForm() else: form = UploadFileForm() return render_to_response('products/addreport.html', {'form': form},context_instance=RequestContext(request)) 
+4
source share
2 answers

I have a pretty similar setup for one of my projects. Do you have any clean method in your form?

Otherwise, I think you can just read the file from form.cleaned_data['file'] :

 import csv def addreport(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): reader = csv.reader(form.cleaned_data['file']) for row in reader: print row else: print form.errors print request.FILES #form = UploadFileForm() else: form = UploadFileForm() return render(request, 'products/addreport.html', {'form': form}) 

If this does not work, try using request.FILES['file'] directly instead of form.cleaned_data['file'] .

Hope this helps.

+5
source

Can you try:

 import csv #In your view line_reader = csv.reader(form.cleaned_data['file']) for row in line_reader: #do something with each row. 
-2
source

Source: https://habr.com/ru/post/1496282/


All Articles