gpt4 book ai didi

Django 在文件上传中引发 MultiValueDictKeyError

转载 作者:行者123 更新时间:2023-12-04 01:37:58 24 4
gpt4 key购买 nike

我已经咨询了很多论坛,我无法得到答案。我已经在我的 Django 应用程序中安装了一个文件上传来将数据保存到我的服务器中。但它不起作用。相反,它会引发 MultiValueDictKeyError。我想问题是没有 request.FILES (因为它在 request.FILES 提到中引发错误),所以文件上传不起作用。这是我的views.py:

def list_files(request, phase_id):
phase = get_object_or_404(Phase, pk=int(phase_id))
if request.method == 'POST':
#form = DocumentForm(request.POST, request.FILES)
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'], phase = phase_id)
newdoc.save()
doc_to_save = request.FILES['docfile']
filename = doc_to_save._get_name()
fd = open(settings.MEDIA_URL+'documents/'+str(filename),'wb')
for chunk in doc_to_save.chunks():
fd.write(chunk)
fd.close()

return HttpResponseRedirect(reverse('list_files'))
else:
form = DocumentForm()

documents = Document.objects.filter(phase=phase_id)

return render_to_response('teams_test/list_files.html',{'documents': documents, 'form':form, 'phase':phase}, context_instance = RequestContext(request)
)

forms.py 中的文档表单:
class DocumentForm(forms.ModelForm):
docfile = forms.FileField(label='Select a file', help_text='max. 42 megabytes')
class Meta:
model = Document

models.py 中的类文档:
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
phase = models.ForeignKey(Phase)

最后,我的html代码:
{% extends "layouts/app.html" %}
{% load i18n user %}

{% block title %}{% trans "Files list" %}{% endblock %}
{% block robots %}noindex,nofollow{% endblock %}


{% block page%}

<div id="page" class="container">
<div class="header prepend-2 span-20 append-2 last whiteboard">
<h2 style="margin-left:-40px">{{ phase.name }} files</h2>

{% if documents %}
<ul>
{% for document in documents %}
<li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}

<form action="{% url list_files phase.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="file" type="file" />
<input id="submit" type="submit" value="Upload file" />
</form>
</div>
</div>
{% endblock %}

我的追溯说:
Exception Type: MultiValueDictKeyError
Exception Value: "Key 'docfile' not found in <MultiValueDict: {}>"
my_dir/views.py in list_files
newdoc = Document(docfile = request.FILES['docfile'], phase = phase_id)

我的 QueryDict 是空的:
POST:<QueryDict: {u'csrfmiddlewaretoken': [u'UZSwiLaJ78PqSjwSlh3srGReICzTEWY1']}>

为什么?我究竟做错了什么?

提前致谢。

最佳答案

您需要更改multipart/form_datamultipart/form-data - 这就是为什么request.FILES为空:由于拼写错误,表单没有按照 Django 期望的方式发送内容。 [编辑:现在已经完成了]

更新 1:此外,不要直接访问 request.FILES,而是尝试依赖模型表单的默认行为,因为这样它就会被适本地作为上传处理。即,newdoc = form.save()应该做所有你需要的,快速浏览一下 - 当模型可以为你做这件事时,你手动保存文件是否有特殊原因?

更新 2:啊,看:您没有为文件上传元素分配名称

从文档:

HttpRequest.FILES A dictionary-like object containing all uploaded files. Each key in FILES is the name from the <input type="file" name="" />. Each value in FILES is an UploadedFile



所以,你需要改变
<input id="file" type="file" />




或者,对于默认的 Django 约定
<input id="id_docfile" type="file" name="docfile"/>

实际上,即使您已经超越了整个 {{form.as_p}},使用 Django 表单来呈现实际字段通常会更好。方法:
{{form.docfile}}

附注。如果您还没有完全阅读它们,我衷心建议您花时间阅读所有 forms documentation

关于Django 在文件上传中引发 MultiValueDictKeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com