I want to submit a form even without uploading an image. But I got the error
**MultiValueDictKeyError**
This is my views.py
filepath = request.FILES['filepath']
See how you can dial with that error:
Use the MultiValueDict's get method to access files.
filepath = request.FILES.get('filepath', False)
If no filepath in FILES, than filepath variable would be False.
One line assignment with ternary operator:
filepath = request.FILES['filepath'] if 'filepath' in request.FILES else False
(Not reccomended) Handle MultiValueDictKeyError exception like in code below:
from django.utils.datastructures import MultiValueDictKeyError
try:
filepath = request.FILES['filepath']
except MultiValueDictKeyError:
filepath = False
Update:
As @Saysa pointed depanding of what steps youd should perform after getting filepath you need to choose which default value would be assigned to filepath, for instance if you have to handle case when filepath not present in FILES at all it's better to use None as default value and check condition as if filepath is None to identify filepath have been submitted, if you need to have some default value simply assign it...
In example above default value is False to make code more apparent for you...
just as an add on to the posting. If you want to check the filepath is given I had to change the type to boolean like this:
if bool(request.FILES.get('filepath', False)) == True:
How about request.FILES.get('filepath') so if no image then filepath should be None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With