Mohit Kumar
Mohit Kumar

Reputation: 732

How to serialize JSON Request data from serializer in Django?

I am trying to serialize a json data through serializers.Serializer

{
    "data": {
        "phoneNumber": "1234567890",
        "countryCode": "+11",
        "otp": "73146",
    }
}

The sterilizer class I wrote for it

class VerifyOtpSerializer(serializers.Serializer):
    phone_number = serializers.CharField(max_length=225, source='phoneNumber', required=True)
    country_code = serializers.CharField(max_length=225, source='countryCode', required=True)
    otp = serializers.CharField(max_length=255, required=True)

enter image description here

and also

I don't know why source is not working, I tried the JSON in the picture below but still it's saying the field is required

enter image description here

Upvotes: 1

Views: 1652

Answers (3)

Jeet Patel
Jeet Patel

Reputation: 1241

The response object you are are sending to your serializer is in correct. The key of your request object should be exactly what you have defined in your serializer.

Try sending this to your serializer.

{
    "data" : {
        "phone_number":"1234567890",
        "country_code":"+11", 
        "otp":"73146"
    }
}

Upvotes: 0

Ajay saini
Ajay saini

Reputation: 2470

Your keys are wrong in the request. as Tom said the source should be an attribute of the model object. so you have to match keys in request and serializer

change phoneNumber > phone_number change countryCode > country_code

Upvotes: 1

Tom Wojcik
Tom Wojcik

Reputation: 6179

source value is what the passed value's key will be changed into. So source value is expected to be on your Model.

The name of the attribute that will be used to populate the field.

What you really want is something that changes camel case payload into a snake case. Just use djangorestframework-camel-case and remove source from your serializer fields.

Upvotes: 1

Related Questions