[Django]-DRF serializer check undefined field

4๐Ÿ‘

โœ…

You can update the validation method like this:

class BoardSerializer(serializers.Serializer):
    user_id = serializers.IntegerField(required=True)
    body = serializers.CharField(required=False)

    def validate(self, attrs):
        unknown =  set(self.initial_data) - set(self.fields)
        if unknown:
            raise serializers.ValidationError("Unknown field(s): {}".format(", ".join(unknown)))
        return attrs

Here, it will check if there is any extra fields passing through the serializer and compare with existing fields. If it exists, then it will throw error(or make is_valid() == false). For more information, you can check this so answer.

๐Ÿ‘คruddra

-1๐Ÿ‘

Because akak is not define in BoardSerializer

You need to add akak in serializer.

You can add custom field akak in seralizer

to catach akak, try this

request.data.get('akak')
๐Ÿ‘คrahul.m

Leave a comment