Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsupported media type Django API

I'm new at Django and my project is in REST when i'm using postman to check URLs it's make this error:

"detail": "Unsupported media type "multipart/form-data; boundary=----WebKitFormBoundaryAU1ShXHTHrfcQr61" in request."

and when using curl this error occurred:

{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}

this is my view for an example URL:

@api_view(["POST"])
def register(request):
    user_data = request.data
    if user_data:
        serializer = UserSerializers(data=user_data)

        if serializer.is_valid():
            registerInfo = {
                'name': serializer.validated_data['name'],
                'degImage': serializer.validated_data['degImage'],
            }

             serializer.save(registerInfo)
             return Response({
                "code": 200,
                "status": "successful",
                "message": "code was sent try to validate code"
                })
        else:
            return Response({
                "status": "error",
                "error": "Bad request"
            })
    else:
        return Response({
            "status": "error",
            "error": "Empty request"
        })

and this is serializer class:

class UserSerializers(serializers.Serializer):
    name = serializers.CharField(required=True)
    degImage = serializers.ImageField(required=True)

    def save(self, validated_data):
        user = Users(
            name=validated_data['name'],
            degImage=validated_data['degImage']
        )
        user.save()
        return user

and the model:

class Users(models.Model):
    name = models.CharField(max_length=20, null=True)
    degImage = models.ImageField(null=False, blank=False, default='detImage')
like image 284
Negar Moshtaghi Avatar asked Dec 18 '17 18:12

Negar Moshtaghi


2 Answers

In postman set, the body as Raw and select JSON from the drop-down and send the request.

or

change the parser in Django rest framework

settings.py

 REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser'
     )
 }
like image 62
Rahul Avatar answered Nov 17 '22 17:11

Rahul


You are probably sending your request with a MIME type that your method is not ready to work with.

Check out the media types in here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types

Can't say much without looking at your request, but i hope it helps.

like image 21
Felipe Menezes Avatar answered Nov 17 '22 19:11

Felipe Menezes