Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for empty request.FILE in Django

Tags:

python

django

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']
like image 542
Iam Moon Avatar asked Jan 22 '16 07:01

Iam Moon


3 Answers

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

like image 192
Andriy Ivaneyko Avatar answered Oct 22 '22 04:10

Andriy Ivaneyko


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:
like image 32
Ercan Dogan Avatar answered Oct 22 '22 05:10

Ercan Dogan


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

like image 1
Raja Simon Avatar answered Oct 22 '22 05:10

Raja Simon