[Solved]-How to check for empty request.FILE in Django

22👍

See how you can dial with that error:

  1. 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.

  2. One line assignment with ternary operator:

    filepath = request.FILES['filepath'] if 'filepath' in request.FILES else False
    
  3. (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:

1👍

How about request.FILES.get('filepath') so if no image then filepath should be None

Leave a comment