I am using django class based view and rest framework
object = self.get_object()
In Detail view if object does not exist and i do get request like
/user/10
then i get this response
{"detail": "not found"}
Now i want to customize that response
like
try:
obj = self.get_object()
except:
raise Exception("This object does not exist")
But thats not working
You could create a custom exception class as below, and it would raise APIException with a
custom message
andcustom status_code
and in your
views
,The response will be like this
{"detail": "This object does not exist"}
NOTE
the
detail
parameter ofCustomAPIException
class takesstr
,list
anddict
objects. If you provide adict
object, then it will return that dict as exception responseUPDATE
As @pratibha mentioned, it's not possible to produce desired output if we use this exception class in Serializer's
validate()
orvalidate_xxfieldName()
methods.Why this behaviour ?
I wrote a similar answer in SO, here Django REST Framework ValidationError always returns 400
How to obtain desired output within the serializer's
validate()
method?Inherit
CustomAPIException
fromrest_framework.exceptions.APIException
instead of fromrest_framework.serializers.ValidationError
ie,
We can implement a custom exception handler function that returns the custom response in case the object does not exist.
In case a object does not exist,
Http404
exception is raised. So, we will check if the exception raised isHttp404
and if that is the case, we will return our custom exception message in the response.After defining our custom exception handler, we need to add this custom exception handler to our DRF settings.