传递空文件时出现 MultiValueDictKeyError

MultiValueDictKeyError when passing empty file

在我的网站上上传图片不是强制性的,因此当留空时​​我得到 MultiValueDictKeyError

但是,如果我传递图像,则不会出现错误。 我错过了什么吗?提前致谢....

views.py

 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>

改用.get(),即:

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

如果找不到它会解析为None。您可以将默认值设置为其他值:

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

参见:https://www.w3schools.com/python/ref_dictionary_get.asp