Django 在文件上传中引发 MultiValueDictKeyError

问题描述 投票:0回答:4

我已经咨询了很多论坛,但没有得到答案。我在 Django 应用程序中安装了文件上传功能,以将数据保存到我的服务器中。但这不起作用。相反,它会引发 MultiValueDictKeyError。我猜问题是没有 request.FILES (因为它在 request.FILES 中提到了一个错误),所以文件上传不起作用。这是我的观点.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']}>

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

提前致谢。

django file-upload
4个回答
21
投票

您需要将

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

更新 1:另外,不要直接访问 request.FILES,而是尝试依赖模型表单的默认行为,因为这样它将被适当地作为上传处理。即,

newdoc = form.save()
应该可以满足您所需的所有需求,快速浏览一下 - 当模型可以为您执行此操作时,您手动保存文件是否有特殊原因?

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

来自文档:

HttpRequest.FILES 一个类似字典的对象,包含所有上传的文件。 FILES 中的每个键都是来自

<input type="file" name="" />
的名称。 FILES 中的每个值都是一个 UploadedFile

所以,你需要改变

<input id="file" type="file" />

或者,对于默认的 Django 约定

<input id="id_docfile" type="file" name="docfile"/>

事实上,通常最好使用 Django 表单来渲染实际字段,即使您已经超越了整个

{{form.as_p}}
方法:

{{form.docfile}}

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


11
投票

将 Post 方法修改为

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}

1
投票

对于尝试上述方法但仍无法找到解决方案的人。这就是我所做的(更新了上一个答案,与最新文档一致):

if request.method == 'POST' and 'filename' in request.FILES:
    doc = request.FILES #returns a dict-like object
    doc_name = doc['filename']
    ...

0
投票

对于尝试上述方法但仍然无法找到解决方案的人。这就是我所做的:

views.py

if request.method == 'POST':
    doc = request.FILES #returns a dict-like object
    doc_name = doc['filename']
    ...
© www.soinside.com 2019 - 2024. All rights reserved.