22👍
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, thanfilepath
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…
2👍
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:
- Django rest framework cache policy
- Python Django Asynchronous Request handling
- Django_auth_ldap no module named ldap
- Django: When to run makemigrations?
- Filter a Django form select element based on a previously selected element
- How to run multiple Django sites on Nginx and uWSGI?
- Global set up in django test framework?
- How do I change a Django Template based on the User's Group?