2

I am trying to save strings, floats and an image via a POST request made to a Django Rest Framework backend:

# My view:

class CreatePost(APIView):
    # tried with and without parser:
    # parser_classes = [FormParser, MultiPartParser]

    def post(self, request):
        serializer = PostSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save(user_id=request.user.pk)
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)


# My serializer:

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ("x", "y")

And my JS frontend:

const postBody = new FormData();
postBody.append('x', 'someValue');
postBody.append('y', 'someValue');

fetch('/api/v1/post', {
    method: 'post',
    body: postBody,
    credentials: 'same-origin',
    headers: {
      'X-CSRFToken': getCookie('csrftoken'),
      'Content-Type': 'multipart/form-data'
    }
  }

However, sending as 'Content-Type': 'multipart/form-data' does not show any values in request.data in my backend. Sending as application/json works, but does not when one of the fields is an image.

How can I process both text and image using form-data? I tried using parsers (FormParser and MultiPartParser) without success.

1
  • This might help Commented Aug 7, 2021 at 13:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.