Search code examples
djangoreactjsdjango-rest-frameworkdjango-file-upload

Django Rest Framework returns bad request when POSTED a file by filepond on React


I have a react app, that uses filepond. Filepond accepts a file, and POSTs it to the server using the following custom header:

const filepondServer = {
  url: `${apiRoot}expenses/receipt_upload`,
  process: {
    headers: {
      Authorization: `Token ${this.props.auth.token}`
    }
  }
};

This goes to a django rest framework view:

class ExpenseReceiptUploadView(APIView):
    permission_classes = [permissions.IsAuthenticated, HasMetis]
    parser_classes = (FileUploadParser,)

    def post(self, request):
        receipt = request.data["file"]
        return Response(status=status.HTTP_201_CREATED)

(I know it needs fleshing out for errors etc, but that will come once it works)

This returns a 400 error, with no further details. If I remove the receipt = request.data["file"] line, it returns a 201, and the server doesn't complain.

To debug this, I tried printing request - this works fine, but request.data results in a 400, as does request.FILES.

The error is very terse, it just says:

2018-12-21 00:01:35,850 [middlewares 70] INFO: {"method": "POST", "path": "/api/v1/operations/expenses/receipt_upload", "user": "Alex", "user_id": 27192835, "device_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", "request_post_body": {"filepond": "{}"}}
2018-12-21 00:01:35,851 [log 228] WARNING: Bad Request: /api/v1/operations/expenses/receipt_upload
[21/Dec/2018 00:01:35] "POST /api/v1/operations/expenses/receipt_upload HTTP/1.1" 400 0

Solution

  • author of FilePond here.

    FilePond will also post the metadata object of the file using the same field name. This works fine on PHP but I'm not sure if this might be troublesome on other backends. I think that's what the error below is trying to indicate.

    "request_post_body": {"filepond": "{}"}

    In versions until FilePond 3.7 the metadata would be posted first. I've swapped this around in 3.7, now the file is posted first, so I'm wondering if you're using 3.7 or an earlier version and if this makes any difference.