Nov 14, 2017 · Updated: Jul 12, 2021 · by Tim Kamanin
Ouch, it looks like it's the longest post title of this blog! But the solution itself is pretty short and straightforward.
When you raise a serializers.ValidationError
, you may be tempted to provide an error as a string argument. Which works, but as a result, this error will be shown under "non_field_errors" key of JSON response.
To set the error as a field-level, instead of passing a string argument, provide a dictionary of type {'field_name': 'Error message'}
.
Here's an example:
def trigger_validator(value):
if value['event_type'] not in ['click', 'submit']:
raise serializers.ValidationError({'event_type': "Please provide a correct type of event"})
class TriggerSerializer(serializers.ModelSerializer):
class Meta:
model = Trigger
fields = ('id', 'event_type', 'events')
validators = [
trigger_validator
]
Hey, if you've found this useful, please share the post to help other folks find it: