'How to format Error message in Json Django

So, I want to format error messages in a json format instead of the HTML it is coming in.

models.py

# AUTH = Regex specified
class Player(models.Model):
    PLAY_MODE = [
        (1, "happy"),
        (2, "sad"),
    ]
    SEX = [
        (1, "Male"),
        (2, "Female"),
    ]
    

    auth = models.CharField(
        max_length=36,
        null=True,
        unique=True,
        validators=[AUTH, MinLengthValidator(36)],
    )
    area = models.ForeignKey(
        "master.Sport", on_delete=models.PROTECT, validators=[MinValueValidator(1)]
    )

serializer.py

 class Playererializer(serializers.ModelSerializer):
      class Meta:
        model = User
        fields = '__all__'

The error format I want

{
  "type": "validation_error",
  "code": "invalid_input",
  "detail": "Crossing the maximum length",
  "attr": "auth"
}

It is coming in HTML format

views.py

def get_player(request, player_id):
    player = Player.objects.get(id=player_id)
    serializer = PlayerSerializer(user)
    # if serializer.is_valid(raise_exception=True):   
    return Response(serializer.data)


Solution 1:[1]

You can use custom exception handling as mentioned in the DRF documentation. For example, create a custom exception:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['type'] = response.default_code 
        response.data["code"] = response.status_code
        response.data["details"] = response.default_detail 
        response.data['att'] = str(exc)
    return response

Then add this to the REST_FRAMEWORK in the settings:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ruddra