django 1.5如何从内存中读取csv [英] django 1.5 how to read csv from memory
问题描述
我试图找出如何读取上传的CSV而不保存到磁盘...
I am trying to find out how to read an uploaded CSV without saving it to disk ...
我被困在form.cleaned_data ['file' ] .read ...我似乎没有得到任何输出
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))
推荐答案
我的项目。
否则,我认为你可以从 form.cleaned_data ['file']读取文件 code>刚好:
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})
如果它不工作,请尝试使用 request.FILES ['file ']
直接而不是 form.cleaned_data ['file']
。
If it doesn't work, try to use request.FILES['file']
directly instead of form.cleaned_data['file']
.
它有助于。
这篇关于django 1.5如何从内存中读取csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!