1

I am using ModelViewSet class to upload a of csv file, do some processing on it and save the output as an excel file in local directory. Now I want to send this excel file back as response for the same request. However I am not able to send back the excel file as response correctly.

serializer.py

class InputSerializer(serializers.ModelSerializer):
    class Meta:
        model = CsvUpload
        fields = ('datafile','created', 'owner', 'filename')
        read_only_fields = ('datafile','created', 'owner', 'filename')

class OutputSerializer(serializers.Serializer):
    excelfile = serializers.FileField()

views.py

...
from .analyzers import MainAnalyser
from xlrd import open_workbook

class FileView(ModelViewSet):
    serializer_class = OutputSerializer
    parser_classes = (MultiPartParser, FormParser,)
    queryset = CsvUpload.objects.all()

    def create(self, request, *args, **kwargs):
        file_serializer = InputSerializer(data=self.request.data)
        file_serializer.is_valid(raise_exception=True)
        file_serializer.save()

        # Call Analyzer functions
        analyzer = MainAnalyzer(self.request.get('datafile'))
        analyzed_xls = analyzer.analyze_files() # returns path to the saved excel file

        # Send back response
        rb = open_workbook(analyzed_xls)
        fileobj = DjangoFile(rb, name='report.xlsx')

        output_serializer = OutputSerializer({'excelfile':fileobj})
        return Response(output_serializer.data)

Most of the approaches I found online used HTTPResponse, but none with ModelViewSet Response. The response with above code is get is

{"excelfile":null}
Niklesh Lalwani
  • 491
  • 4
  • 5

0 Answers0