Validation Multiple Files


Hi guys!

I wanna upload and validate multiple files from a forms.FileField.

I have written the following line in the to upload multiple files:

files_field = forms.FileField(widget=forms.ClearableFileInput(attrs={‘multiple’: True}))

But now i wanna validate the number of files that the user can upload, the extension and the size of each file. Some idea?


(Vitor Freitas) #2

You can iterate through the uploaded files in your view or form:

uploaded_files = request.FILES.getlist('files_field')

if len(uploaded_files) > 3:
    # do something...

for file in uploaded_files:
    print(, file.size)
    # do something with file name, extract extension, validate the size, etc


Thanks vitor!

I was thinking in that method but im worried with the security of this method. I have a doubts about where are theses files saved during the validation process. Are these files located in the memory or in temporary folder during this process? Because i save these files in the system using the following function:

def handle_uploaded_file(path, file):
destination = open(path + "/" + str(, 'wb+')
for chunk in file.chunks():

(Vitor Freitas) #4

It depends on the size of the file. If the submitted file is less than 2.5MB, Django handle it in memory. If the file is larger than 2.5MB, Django will save the uploaded file in the filesystem in the /tmp/ directory, regardless of your validation or anything.

You can fine tune this 2.5MB using the FILE_UPLOAD_MAX_MEMORY_SIZE setting.

The most secure way to handle uploaded files in a Django application is using the built-in FileSystemStorage:

from import FileSystemStorage

uploaded_file = request.FILES['document']
fs = FileSystemStorage(), uploaded_file)

This will handle permissions, conflicting name, etc