Я новичок в Django и относительно нов в python. Я написал программу, которая позволяет пользователю загружать файл Excel. Файл Excel сохраняется в форму в Django. Я не могу понять, как сохранить загруженный файл в мою форму после запуска сценария поверх него (сценарий использует pandas). Когда я пытаюсь загрузить файл, я получаю '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)