Handling custom validation errors in Django REST Framework with proper response formatting
I'm attempting to set up I'm working on a project and hit a roadblock. I'm building a feature where I need help solving I'm having a hard time understanding I've searched everywhere and can't find a clear answer..... I'm working on a Django REST Framework (DRF) project and I need to implement custom validation on my serializer fields. Specifically, I want to raise a custom validation behavior when a user tries to submit a negative value for a certain field. However, I'm struggling to format the response in a way that it includes both the field name and a custom behavior message. I've tried using the `validate_<fieldname>` method in my serializer, but the behavior message returned isn't structured as I'd like it to be. Here's a snippet of my serializer code: ```python from rest_framework import serializers class MySerializer(serializers.Serializer): positive_integer = serializers.IntegerField() def validate_positive_integer(self, value): if value < 0: raise serializers.ValidationError('The value want to be negative.') return value ``` When I test this by submitting a negative integer, I receive a response like this: ```json { "non_field_errors": [ "The value want to be negative." ] } ``` What I want instead is for the behavior to be linked to the `positive_integer` field, like this: ```json { "positive_integer": [ "The value want to be negative." ] } ``` I've tried overriding the `create` and `update` methods but I need to seem to get it right. How can I achieve this custom behavior formatting while ensuring that the errors are directly tied to the relevant fields? I'm using Django 3.2 and DRF 3.12. What's the best practice here? I recently upgraded to Python 3.11. Has anyone else encountered this? This issue appeared after updating to Python stable. This is happening in both development and production on Ubuntu 20.04. I'm coming from a different tech stack and learning Python.