Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MultiValueDictKeyError when passing empty file

In my website uploading picture is not compulsory, Therefore when left empty I get
MultiValueDictKeyError

But if i pass an image is dont get an error.
Am I missing some thing?? Thanks in advance….

views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 if request.method == "POST":
        FirstName = request.POST['FirstName']
        LastName = request.POST['LastName']
        image = request.FILES['image'] #This one 
        age = request.POST['age']
        gender = request.POST['gender']
        address = request.POST['address']
        PhoneNumber = request.POST['PhoneNumber']
        EmailAddress = request.POST['EmailAddress']
        Password = request.POST['Password']
        RepeatPassword = request.POST['RepeatPassword']
        BloodGroup = request.POST['BloodGroup']

        try:
            if Password == RepeatPassword:
                Patient.objects.create(FirstName=FirstName, LastName=LastName, image=image, age=age, gender=gender,
                                       address=address, PhoneNumber=PhoneNumber, EmailAddress=EmailAddress, BloodGroup=BloodGroup)
                return redirect('login')
            else:
                messages.success(
                    request, ("Passwords do not match. Please try again"))
        except Exception as e:
            messages.success(
                request, ("This email already exists. Try again with another email or recover your account"))
    return render(request, 'signup.html')

HTML

<div class="input-div one">
        <div class="i">
            <ion-icon name="image-sharp"></ion-icon>
        </div>
        <div class="div">
            <h5>Photo</h5>
            <input type="file" class="input" name="image">
        </div>
    </div>

>Solution :

Use .get() instead, i.e:

image = request.FILES.get('image')

It will resolve to None if it can’t find it. You can set the default to something else with:

image = request.FILES.get('image', "New default that isn't None")

See: https://www.w3schools.com/python/ref_dictionary_get.asp

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading