Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.5 how to read csv from memory

I am trying to find out how to read an uploaded CSV without saving it to disk ...

I'm stuck at form.cleaned_data['file'].read ... I don't seem to get any output

If I can only figure out how to get output, then I can write an appropriate function to deal with the lines of data.

#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))
like image 243
Simply Seth Avatar asked Oct 04 '22 06:10

Simply Seth


1 Answers

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

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

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 it doesn't work, try to use request.FILES['file'] directly instead of form.cleaned_data['file'].

Hope it helps.

like image 56
Hieu Nguyen Avatar answered Oct 08 '22 02:10

Hieu Nguyen