5

我正在尝试找出如何在不将其保存到磁盘的情况下读取上传的 CSV...

我被困在 form.cleaned_data['file'].read ...我似乎没有得到任何输出

如果我只能弄清楚如何获得输出,那么我可以编写一个适当的函数来处理数据行。

#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

2 回答 2

6

我的一个项目有非常相似的设置。您的表格中有任何干净的方法吗?

否则,我认为您可以从以下位置读取文件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})

如果不起作用,请尝试request.FILES['file']直接使用而不是form.cleaned_data['file'].

希望能帮助到你。

于 2013-08-10T15:24:39.053 回答
-2

你能试一下吗:

import csv

#In your view
line_reader = csv.reader(form.cleaned_data['file'])
for row in line_reader:
    #do something with each row.
于 2013-08-10T06:11:06.567 回答