1

Using django rest framework 3.1.1, I have the following serializer:

class CommentSerializer(ContentSerializer):

    created_by = UserSerializer(required=False)
    content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)

    class Meta:
        model = Comment

While the content field respects the required=False parameter, but created_by does not, which in result, gives me a list of "This field is required" validation errors inside the UserSerializer:

{"created_by":{"username":["This field is required."],"user_permissions":["This field is required."],"password":["This field is required."],"groups":["This field is required."],"profile_picture":["This field is required."]}}

According to the documentation section "Dealing with nested objects" it demonstrates the usage with a serializer.

What I have tried:

  • My previous question about this and tried adding get_validation_exclusions did not help as I believe it's already been attended in this issue.

  • Changing created_by to created_by = serializers.PrimaryKeyRelatedField(required=False) worked, but that is not what I want.

  • A quick search in the existing issue shows I am not the only one having this problem: https://github.com/tomchristie/django-rest-framework/issues/2719

UPDATE:

I have created a couple of test cases (see here) but couldn't replicate the issue, looks like it is only happening via Ajax Post.

Community
  • 1
  • 1
James Lin
  • 25,028
  • 36
  • 133
  • 233

1 Answers1

0

I added read_only=True to the created_by field, now it's working fine.

class CommentSerializer(ContentSerializer):

    created_by = UserSerializer(required=False, read_only=True)
    content = serializers.PrimaryKeyRelatedField(queryset=Content.objects.all(), required=False)

    class Meta:
        model = Comment
James Lin
  • 25,028
  • 36
  • 133
  • 233