Django REST Framework how to specify error code when raising validation error in serializer

You can raise different exceptions like:

from rest_framework.exceptions import APIException
from django.utils.encoding import force_text
from rest_framework import status


class CustomValidation(APIException):
    status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    default_detail="A server error occurred."

    def __init__(self, detail, field, status_code):
        if status_code is not None:self.status_code = status_code
        if detail is not None:
            self.detail = {field: force_text(detail)}
        else: self.detail = {'detail': force_text(self.default_detail)}

you can use this in your serializer like:

raise CustomValidation('Duplicate Username','username', status_code=status.HTTP_409_CONFLICT)

or

raise CustomValidation('Access denied','username', status_code=status.HTTP_403_FORBIDDEN)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)