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)
Use django-rest-framework custom exception handler http://www.django-rest-framework.org/api-guide/exceptions/
def custom_exception_handler(exc, context=None):
response = exception_handler(exc, context)
if response is not None:
if response.data['detail'] == 'Duplicate Username':
response.data['username'] = response.data.pop('detail')
response.status_code = status.HTTP_409_CONFLICT
return response