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))
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.
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