Python:在Django中处理上传的.txt文件时出现MultiValueDictKeyError

0 投票
1 回答
1189 浏览
提问于 2025-04-18 17:34

抱歉我问了一个简单的问题,这个问题之前在这个网站上已经被问过并回答过,但我刚开始学习Django,参考那些早期的 问题文档,我还是没能解决我的问题。我有一个简单的应用程序,可以让用户上传.txt文件,这个功能是可以用的。现在我想在这个应用程序中增加一个功能,对上传的文本文件进行一些简单的操作,但我在尝试实现这个功能的那一行代码时,总是遇到MultiValueDictKeyError错误。以下是我想实现的功能(这是sample_functions.py):

def print_file_contents(file_object):
    with open(file_object) as f:
        f = f.decode("utf-8")
        f = f.read()

        print f

这是我的models.py:

from django.db import models
from django.forms import ModelForm

class Upload(models.Model):
    pic = models.FileField("Choose a text file to upload", upload_to="text/")    
    upload_date=models.DateTimeField(auto_now_add =True)

# FileUpload form class.
class UploadForm(ModelForm):
    class Meta:
        model = Upload

这是我的views.py:

from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from uploader.resources.sample_functions import print_file_contents

# Create your views here.
def home(request):
    if request.method=="POST":
        img = UploadForm(request.POST, request.FILES)       
        if img.is_valid():

            print_file_contents(request.FILES[img])

            img.save()
            return HttpResponseRedirect(reverse('fileupload'))
    else:
        img=UploadForm()
    images=Upload.objects.all()
    return render(request,'home.html',{'form':img,'images':images})

这是我的home.html:

{% load staticfiles %}

<link rel="stylesheet" type="text/css" href="{% static 'uploader/style.css' %}" />
<div style="padding:40px;margin:40px;border:1px solid #ccc">

    <body>
    <center><h2>Here Be Dragons</h2></center>
    <p>Lorem ipsum...</p>
    <p></p>
    </body>


    <center><form action="#" method="post" enctype="multipart/form-data">
        {% csrf_token %} {{form}} 
        <input type="submit" value="Upload" />
    </form></center><p></p><p>Uploaded files:</p>
    {% for img in images %}
        {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
        ({{img.upload_date}})<hr />
    {% endfor %}
</div>

这是错误追踪信息:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.6.5
Python Version: 2.7.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'uploader')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Douglas\Desktop\sample\uploader\views.py" in home
  14.             print_file_contents(request.FILES[img])
File "c:\Python27\lib\site-packages\django\utils\datastructures.py" in __getitem__
  301.             raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /upload/
Exception Value: '<uploader.models.UploadForm object at 0x000000000340AEF0>'

有没有人知道我该如何修改views.py中的这一行代码print_file_contents(request.FILES[img]),或者工作流程中的其他部分,以便能够打印出上传文件的内容?我非常感激你能提供的任何建议。

1 个回答

2

我不太明白你想要做什么。img代表的是整个表单,而不是图片的那个部分。图片的部分叫做“pic”,所以你应该用request.FILES['pic']来获取它。

你可以通过在你的视图中打印或者记录request.FILES.keys()来自己发现这个问题。

撰写回答