django rest framework: set field-level error from serializer validate() method

前端 未结 4 1476
忘掉有多难
忘掉有多难 2021-02-02 07:08

I have a serializer that validates fields based on the values of other fields, In the error response I would like to show each field error as a field error as opposed to showing

4条回答
  •  忘掉有多难
    2021-02-02 07:43

    If you have logic that applies to all the fields, you can still get the desired result by doing this:

    def validate(self, data):
        for key, value in data.items():
            # checks if value is empty
            if not value:
                raise serializers.ValidationError({key: "This field should not be left empty."})
    
        return data
    

提交回复
热议问题