'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
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 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bob |
