【发布时间】:2019-03-03 18:37:32
【问题描述】:
我无法将 excel 文件上传到我的 django 应用程序。这是一个非常简单的应用程序,它应该允许用户上传一个包含 3 列的 excel 文件。应用程序将读取该文件的内容并将其处理成一堆计算
这是我的 forms.py:
class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
settings.py:
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler"]
views.py:
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
if request.method == 'POST':
form = InputForm(request.POST,request.FILES['FileLocation'])
if form.is_valid():
book = xlrd.open_workbook(request.FILES('FileLocation'))
for sheet in book.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
print(number_of_rows)
我在表单中上传文件,它给了我一个错误:
AttributeError at /app/analyze/
'ExcelInMemoryUploadedFile' object has no attribute 'get'
Request Method: POST
Request URL: http://127.0.0.1:8000/data/analyze/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
Exception Location: C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
Python Executable: C:\Python36\python.exe
Python Version: 3.6.4
我还可以使用以下 views.py 代码成功上传 .csv 文件:
def analyze(request):
c={}
context = RequestContext(request)
c.update(csrf(request))
abc=['a','b','c']
if request.method == 'POST':
form = InputForm(request.POST,request.FILES)
dataType = request.POST.get("DataType")
print(dataType)
if form.is_valid():
cd = form.cleaned_data #print (cd)
a = TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')
#print (request.FILES.keys())
data = csv.reader(a)
row1csv = next(data)
region = row1csv[0]
metric = row1csv[2]
我尝试过 django-excel 时出现同样的错误。
【问题讨论】:
-
我认为显示
InputForm的代码会有所帮助,看来这就是问题所在。 -
这个代码也是错误的:
book = xlrd.open_workbook(request.FILES('FileLocation')),它应该是request.FILES['FileLocation']的方括号。但这是一个不同的错误,它不会在表单的小部件中产生错误。 -
感谢您的审阅。 (1) 你是指 InputForm 的 HTML 代码吗? (2) 我尝试在语句中将我的代码更改为
request.FILES['FileLocation']。同样的错误。 -
是的,正如我所说,您的错误与方括号无关,但是在修复第一个错误后您会收到一个新错误 :-) 对不起,我的错,错过了
InputForm代码在顶部。 -
您没有正确初始化表单:
form = InputForm(request.POST, request.FILES['FileLocation'])应该是form = InputForm(request.POST, request.FILES)。这里需要一个字典 (QueryDict),而不是上传的文件。
标签: django excel python-3.x file-upload