Django / Pandas-当我尝试将文件保存到表单时,上传的文件在“ /”处获取“ MultiValueDictKeyError错误”,然后是整个数据库

时间:2020-01-27 21:19:58

标签: python django django-forms django-views django-pandas

我是Django的新手,而python是新手。我编写了一个程序,允许用户上传excel文件。 Excel文件将保存到Django中的表单中。在脚本上运行脚本后(脚本使用熊猫),我无法弄清楚如何将上传的文件保存到表单中。当我尝试上传文件时,当我尝试将文件保存到表单时,出现“ MultiValueDictKeyError at /”,然后是整个数据库。我的目标是使用户能够下载新文件。我的代码在下面。

views.py

def file_list(request):
     files = File.objects.all()
     return render(request, 'file_list.html',{
         'files':files
     })

def upload_file(request):
if request.method == 'POST':
    uploaded_file = request.FILES['xlsx']
    import pandas as pd
    df = pd.read_excel(uploaded_file)
    df.dropna(subset=['Email', 'First Name'], inplace=True)
    df.fillna('', inplace=True)
    df = df.applymap(str)
    df['Company'] = df['Company'].str.upper()
    df['First Name'] = df['First Name'].str.lower()
    df['First Name'] = df['First Name'].str.capitalize()
    df['Last Name'] = df['Last Name'].str.lower()
    df['Last Name'] = df['Last Name'].str.capitalize()
    df['Company'] = df['Company'].str.lower()
    df['Company'] = df['Company'].str.capitalize()
    df['Title'] = df['Title'].str.lower()
    df['Title'] = df['Title'].str.title()
    form = FileForm(request.POST, request.FILES[df.to_csv(index=False)])
    if form.is_valid():
        form.save()
        return redirect('file_list')

else:
    form = FileForm()
    return render(request, 'upload_file.html', {
    'form': form
    })

forms.py

from django import forms
from .models import File

class FileForm(forms.ModelForm):
    class Meta:
         model = File
         fields = ('xlsx', )

models.py

 from django.db import models
 # Create your models here.
 class File(models.Model):
      xlsx = models.FileField(upload_to='files/xlsx/')


Internal Server Error: /files/
Traceback (most recent call last):
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 828, in _resolve_lookup
    current = current[bit]
TypeError: 'FieldFile' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\samko\Attempt2\Upload\views.py", line 10, in file_list
    return render(request, 'file_list.html',{
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 986, in render
    output = self.filter_expression.resolve(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 670, in resolve
    obj = self.var.resolve(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 795, in resolve
    value = self._resolve_lookup(context)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 836, in _resolve_lookup
    current = getattr(current, bit)
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 61, in url
    self._require_file()
  File "C:\Users\samko\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\files.py", line 38, in _require_file
    raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

1 个答案:

答案 0 :(得分:0)

您的问题在这里-您无法通过这种方式访问​​请求对象中的文件:

request.FILES[df.to_csv(index=False)])

它将给出MultipleValueDictKeyError。另外,请求数据也受到保护,不会被修改。

由于您已经使用表格来获取uploaded_file,因此您可以将生成的csv保存到DB:

from django.core.files import File

file_obj = File(xlsx=File(df.to_csv(index=False)))
file_obj.save()

您可能想详细了解file objectsfile upload