1

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

2
  • Can you try phone_number instead of phoneNumber. Commented Jun 4, 2021 at 14:06
  • source is not the key that will be passed for the field. source is the name of the field / attribute on the model class. Also see Why not upload images of code/errors when asking a question? Commented Jun 4, 2021 at 14:15

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

I can't because app is in prod 😔
then change field name in your serilaizer to match with the JSON
yeah, it's the last option
0

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"
    }
}

2 Comments

but I can't alter the json data
If you can't change the JSON data and if you can't update the serilizer as it is in production, then perhaps there is nothing that you and the community could do fix the issue.

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.