Home > Enterprise >  MultiValueDictKeyError at /profiles/ uploading file
MultiValueDictKeyError at /profiles/ uploading file

Time:10-06

I am using the django framework. And I just want to upload an image.

So I have this:

views.py:


# Create your views here.
def store_file(file):
    with open("temp/mensschappy.png", "wb ") as dest:
        for chunk in file.chunks():
            dest.write(chunk)


class CreateProfileView(View):
    def get(self, request):
        form = ProfileForm()
        return render(request, "profiles/create_profile.html", {
            "form": form
        })

    def post(self, request):
        submitted_form = ProfileForm(request.POST, request.FILES)

        if submitted_form.is_valid():
            store_file(request.FILES["image"])
            return HttpResponseRedirect("/profiles")

        return render(request, "profiles/create_profile.html", {
            "form": submitted_form
        })


and the html:

{% load static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Create a Profile</title>
    <link rel="stylesheet" href="{% static "profiles/styles.css" %}">
  </head>
  <body>
    <form action="/profiles/" method="post" enctype="multipart/form-data">
      {% csrf_token %} {{ form }}

      <button>Upload!</button>
    </form>   
  </body>
</html>

but if I try to upload an image. I get this error:

MultiValueDictKeyError at /profiles/

'image'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/profiles/
Django Version:     4.1.1
Exception Type:     MultiValueDictKeyError
Exception Value:    

'image'

Exception Location:     C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in __getitem__
Raised during:  profiles.views.CreateProfileView
Python Executable:  C:\Python310\python.exe
Python Version:     3.10.6
Python Path:    

['C:\\Users\\engel\\Documents\\NVWA\\software\\blockchainfruit\\schoolfruitnvwa',
 'C:\\Python310\\python310.zip',
 'C:\\Python310\\DLLs',
 'C:\\Python310\\lib',
 'C:\\Python310',
 'C:\\Python310\\lib\\site-packages']

Server time:    Thu, 06 Oct 2022 08:38:50  0000

So my question is: how to tackle this?

Thank you

ProfileForm:

from django import forms

class ProfileForm(forms.Form):
    upload_file = forms.FileField()

CodePudding user response:

It should be request.FILES['uploaded_file'], as the field_name after rendering the form becomes the name attribute of that particular field in HTML.

  • Related