Search code examples
pythondjangopandasmulti-value-dictionary

How to read or save a file from MultiValueDict in Django


I'm sending a excel file from Angular to Django. I want to read the file using Pandas and perform some operations in the file, but I'm not sure how to do it.

class fileupload(APIView) :
    def post(self, request): 
        f = request.FILES
        print(f)

When I print, it shows below,

<MultiValueDict: {'excelfile': [<InMemoryUploadedFile: New_Excel.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}>

Here, I want to save this file to some location and use pandas to perform operations or if possible, directly would need to read the file using pandas. I'm new to Django and Pandas so if anything is wrong, please help.. Thanks in advance


Solution

  • from django.core.files.storage import default_storage    
    from django.core.files.base import ContentFile
    file_objs = request.data.getlist('files')
    for file_obj in file_objs:
        path = default_storage.save(settings.MEDIA_ROOT, ContentFile(file_obj.read()))
        print("images path are",path)