发送附件时出现MultiValueDictKeyError

时间:2016-03-07 14:30:00

标签: python django

<script type="text/template" id="_escalation-container">
    <div class="response-container">
        <form action="" class="escalation-form" enctype="multipart/form-data">{% csrf_token %}
                <a href="#" class="add-scripted-message">{% trans "Add Message" %}</a>
            </div>
            <div class="sub-content-footer" style="margin-top: 10px;">
                <input id="file" type="file" name="file"/>
            </div>
        </form>
    </div>
</script>

我看Django official documentation并尝试做那里写的内容。

View.py:

if request.POST:
    form = EscalationForm(request.POST, request.FILES)
    if form.is_valid():
        escalation_message = form.save(commit=False)
        handle_uploaded_file(request.FILES['file'])
        escalation_message.save()

handle_uploaded_file完全相同;

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

EscalationForm.py:

class EscalationForm(forms.ModelForm):
    class Meta:
        model = EscalationMessage

我的模特是:

class EscalationMessage(models.Model):
    file = models.FileField(null=True, blank=True, upload_to='.')

另外,我将这些添加到我的settings.py;

FILE_UPLOAD_HANDLERS = [
    "django.core.files.uploadhandler.MemoryFileUploadHandler",
    "django.core.files.uploadhandler.TemporaryFileUploadHandler"
]

然而,当我尝试发送附件时,它给出了

File "/Users/mk/Documents/interaction/views.py", line 169, in create_escalation_message
    escalation_message.file = EscalationMessage(file=request.FILES['file'])
  File "/Users/mk/Documents/venvs/lib/python2.7/site-packages/django/utils/datastructures.py", line 322, in __getitem__
    raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'file'"

我是网络开发的新手,我正在编写一个迷你演示版。我试图发送带有附件的消息,然后我搜索了一个例子,它给出了这个错误。你对这个错误有什么看法吗?

谢谢

1 个答案:

答案 0 :(得分:0)

文件上传必须使用POST方法。将您的form标记更改为:

<form action="" method="post" class="escalation-form" enctype="multipart/form-data">