how to upload multiple files and use charfields at the same time in django rest framework?

Viewed 84

Im pretty new in this field, so I will try to explain this the best way I can.

Im trying to upload two different optional files (this means that it is not required to upload them) and also have two optional CharFields as inputs in the same API method.

I can better explain this by showing what my views.py, my serializers.py is like and how I would like to be able to enter it in postman.

With this, I can upload a file, but after this I have a traceback return None as HttpResponse, because the code cannot continue.

views.py

class FileUploadView(APIView):
    parser_classes = (FileUploadParser,)

    @swagger_auto_schema(request_body=FileSerializer,
                         responses={
                             HTTP_200_OK: PostSuccessResponseSerializer,
                             HTTP_400_BAD_REQUEST: PostErrorResponseSerializer
                         }
                         )
    def post(self, request):
        # Upload two different OPTIONAL files
        file_1 = request.data.get('file_1', None)
        file_2 = request.data.get('file_2', None)

        # CharField optional inputs
        user_input = request.data.get('user_input') or ''
        foo_char = request.data.get('model_filename') or ''

        # Do something with the files
        ...

        # do something with the CharFields inputs
        ...

        return Response(f'Success!', status=HTTP_200_OK)

serializer.py

class FileSerializer(serializers.Serializer):
    file = serializers.FileField(allow_empty_file=False, use_url=False)
    user_input = serializers.CharField()
    foo_char = serializers.CharField()

Postman

postman_sample

0 Answers
Related