Django:我尝试访问上传的文件时遇到MultiValueDictKeyError

时间:2020-07-11 17:47:10

标签: python django

我正在尝试制作一个简单的Django Web应用程序,当您发送两个图像时,它将创建另一个图像文件,该文件的两个图像在下面的脚本(join_pics())旁边。

为简单起见,我只想获取上载的文件,运行脚本,然后将文件作为下载返回给用户。没有将文件保存到SQL或服务器。 我知道我必须检查文件格式和大小等。所有这些都可以通过使用JS和Python脚本中的故障保护(待实现)来解决。

问题是我似乎无法访问上传的文件。我尝试了几种方法,在StackOverflow和其他网站上查看了各种教程和其他文章,等等。

这是我的代码:

# forms.py

class ThingyForm(forms.Form):
    file1 = forms.CharField(label="file1", widget=forms.FileInput(), required=False)
    file2 = forms.CharField(label="file2", widget=forms.FileInput(), required=False)
    pwd1 = forms.CharField(label='Pwd1', max_length=32, widget=forms.PasswordInput(), required=False)
    pwd2 = forms.CharField(label='Pwd2', max_length=32, widget=forms.PasswordInput(), required=False)
# views.py:

def thingy(request):
    form = ThingyForm(request.POST or None, request.FILES or None)

    if str(request.method) == 'POST':
        if form.is_valid():
            print('Form Validated.') # Just to know that 
            pwd1 = form.cleaned_data['pwd1'] #a password in case the user wants to zip the file with a password
            pwd2 = form.cleaned_data['pwd2'] #the password is repeated in order to prevent typos
            if pwd1 == pwd2:
                file1 = form.cleaned_data['file1']
                file2 = form.cleaned_data['file2']
                if (str(file1) != '') and (str(file2) != ''):
                    messages.success(request, 'Procedure successful.')
                    c_file1 = request.FILES['file1'].read()
                    c_file2 = request.FILES['file2'].read()
                    join_pics(c_file1, c_file2, pwd1)


                else:
                    messages.error(request, 'You must provide two files.')
            else:
                messages.error(request, 'The passwords do not match. Please reenter them.')
        else:
            print('Errors ' + str(form.errors))
            messages.error(request, 'No bueno.')
    context = {
        'form': form
    }
    return render(request, 'thingy.html', context)

# urls.py:

from django.urls import path

from .views import index, thingy

urlpatterns = [
    path('', index, name='index'),
    path('thingy/', thingy, name='thingy'),
]

<!-- thingy.html: -->

{% load bootstrap4 %}
<!DOCTYPE html>
<html lang="en">
<head>
    {% bootstrap_css %}
    <meta charset="UTF-8">
    <title>Thingy</title>
</head>
<body>
    <div class="container">
        <h1>He need some milk!</h1>
        {% bootstrap_messages %}

        <form action="{% url 'thingy' %}" method="post" class="form" autocomplete="off" enctype="multipart/form-data">
            {% csrf_token %}
            {% bootstrap_form form %}
            {% buttons %}
                <button type="submit" class="btn btn-primary">MakeItSo</button>
            {% endbuttons %}
        </form>

    </div>

{% bootstrap_javascript jquery='full' %}
</body>
</html>

提交表单时,出现以下错误:

MultiValueDictKeyError at /thingy/

'message'

Request Method:     POST
Request URL:    http://localhost:8000/thingy/
Django Version:     3.0.8
Exception Type:     MultiValueDictKeyError
Exception Value:    

'message'

(...)
During handling of the above exception ('message'), another exception occurred: 

\views.py in thingy

                        c_file1 = request.FILES['file1'].read()

     

据我所知, request.FILES 没有返回正确的数据。但是,我不知道如何使用最近上传的文件。 我是Django的新手,并且相信我已经发布了所有有助于查找错误的信息,但如果有帮助,我很乐意发布更多代码。

0 个答案:

没有答案