2

This is surely a problem in my understanding of how the serializer should work.

After changing a property permissions on my serializer, I found out that my Author nested object is turning out empty on the validated_data.

Here's my code :

class ThreadSerializer(serializers.Serializer):
    class Meta:
            model = Thread
            queryset=Thread.objects.all()
            fields = ('id', 'title', 'description', 'author', 'created_at')

    pk = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=False, max_length=100)
    description = serializers.CharField(style={'base_template': 'textarea.html'}, required=False)
    author = AuthorSerializer()
    created_at = serializers.DateTimeField(required=False)

    def create(self, validated_data):
        """
        Create and return a new `Thread` instance, given the validated data.
        """
        author_data = validated_data.pop('author')
        if author_data:
            author = Author.objects.get_or_create(**author_data)
            validated_data['author'] = author

        return Thread.objects.create(**validated_data)

The payload is also quite simple: { "title": "2", "description": "testing nested objects", "author": { "name": "ron", "email" : "[email protected]" }}

Yet, on the validated_data variable all I see is an empty OrderedDict.

Can someone point me to where I should be fixing this?

2
  • so you are absolutely sure that validated_data is empty? also noticed that you are subclassing from regular Serializer, not ModelSerializer which is required to use Django models Commented Aug 7, 2015 at 19:59
  • After testing the client side of the app I found out it was actually a problem of the json data being passed to DRF as a form and not as contentType: "application/json; charset=utf-8". @miki725 I also did not realise the ModelSerializer needed to be used. Thank you for pointing that out. Commented Aug 10, 2015 at 10:42

1 Answer 1

1

The problem here was on the client-side.

Information was being passed as form-data and not as application/json on the ajax request.

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

1 Comment

Thank you for pointing out this thing. I had the same problems and was devastatingly looking for the answer for a week.

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.