I am newbie in Django and Django REST Framework. I have the following serializer class which I am using to upload a file along other information. But, while I run the API endpoint with uploaded file, the result is something like this:
HTTP 415 Unsupported Media Type
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Unsupported media type \"multipart/form-data; boundary=----WebKitFormBoundaryybZ07gjZAqvcsZw3\" in request."
}
I tried hard by googling to solve this issue, but cannot come out in a solution, so here is my serializer and API views.
Serializer:
class ExampleSerializer(serializers.Serializer):
example_id = serializers.IntegerField()
description = serializers.CharField(allow_blank=True)
example_file = serializers.FileField(allow_empty_file=True)
def create_requirement_line(self):
request = self.context['request']
requirement_line = ExampleService().example_method(
example_id=self.validated_data['example_id'],
description=self.validated_data['description'],
example_file=self.validated_data['example_file']
)
return requirement_line
View:
class RequirementLineAPIView(BaseCreateAPIView):
serializer_class = ExampleSerializer
parser_classes = (FormParser,)
def post(self, request, format=None,*args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
try:
example_variable = serializer.example_method()
return Response(example_variable, status=status.HTTP_200_OK)
except ValidationError as e:
return Response(e.message, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
You should use the MultiPartParser instead of the FormParser if you're sending multipart/form-data.
Raised if there are no parsers that can handle the content type of the request data when accessing request.DATA or request.FILES.
check Django REST Framework2 documentation
import suitable parser
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
class SampleView(APIView):
parser_classes = (MultiPartParser,FormParser,JSONParser)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With