我正在尝试使用Django上传csv文件并计划解析CSV文件。但是这段代码无法上传文件并继续进入else条件。这段代码有什么问题?谢谢!
Old Class New Class
ASN1Object ASN1Primitive
ASN1Encodable ASN1Object
DEREncodable ASN1Encodable
DERObject ASN1Primitive
DERString ASN1String
DERObjectIdentifier ASN1ObjectIdentifier
X509Name X500Name
DERInteger ASN1Integer
DEREnumerated ASN1Enumerated
X509Attributes X509AttributeIdentifiers
X509Extension Extension
template.html
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import csv
import codecs
from items.models import UploadFileForm
def handle_files(f):
reader = csv.DictReader(open(f))
for row in reader:
print row
def home(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_files(request.FILES['file'])
return HttpResponseRedirect('/workflow/')
else:
print form.errors
print request.FILES
return HttpResponseRedirect('/workflow/upload')
else:
form = UploadFileForm()
return render(request, 'template.html', {'formset': form})
forms.py
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<input type="file" name="csv_file" />
<input type="submit" value="Upload" />
</form>
答案 0 :(得分:0)
相反,您可以尝试(除非您启用了验证,否则无需检查表单是否有效):
def home(request):
if request.method == "POST":
if request.FILES:
handle_files(request.FILES['file'])
return HttpResponseRedirect('/workflow/')
else:
return HttpResponseRedirect('/workflow/upload')
else:
form = UploadFileForm()
return render(request, 'template.html', {'formset': form})