Jason Morse
Jason Morse

Reputation: 11

How to return custom response in django rest?

I want to know how can we return error/success custom response in Django rest instead of serializer response. For example I want to return the response in the following format

{
  'status':'Error',
  'reson':'Reason'
}

whereas serializer return errors as in the following format

 {'username': ['This field is required.'], 
     'password': ['This field must be at least 8 chars'],
     'email': ['This field cannot be blank']
    }

How to customize this error response? Please help. Thanks in advance.

Upvotes: 1

Views: 1527

Answers (2)

Mehedi Hasan
Mehedi Hasan

Reputation: 11

def func(request):

try:   
        return Response(serializer.data)

    else:
        Response({'detail': 'Write your custom message here'},
                 status=status.HTTP_400_BAD_REQUEST)
except:
    return Response({'detail': 'Write your custom message here'}, status=status.HTTP_400_BAD_REQUEST)

Upvotes: 1

Arzu Huseynov
Arzu Huseynov

Reputation: 210

The simple solution is updating serializer.data dictionary from your view.

serializer.data['status'] = 'Error'
serializer.data['reason'] = 'Reason'

return Response(serializer.data)

There are better solutions such as creating custom decorators or creating custom Response object which inherited from Response class. It`s up to you.

Upvotes: 1

Related Questions