33đź‘Ť
âś…
1 Overwrite the create method on the view and put something like this:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"Success": "msb blablabla"}, status=status.HTTP_201_CREATED, headers=headers)
2 In the code above, change raise_exception
to False
and return whatever you want if the serializer is not valid. i.e.:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid(raise_exception=False):
return Response({"Fail": "blablal", status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"Success": "msb blablabla"}, status=status.HTTP_201_CREATED, headers=headers)
You are using CBV so you’ll be able to create your custom generic classes that extends DRF’s classes, and DRY
however, I’d say that you shouldn’t add “success” or “fail” in your responses… if the http code is 2xx the user will know it was OK, 4xx when the request has a problem and 5xx when there was a error on your code (or the server), you don’t need to repeat that information on the body of your response, just use the HTTP status codes
Hope this helps
👤pleasedontbelong
Source:stackexchange.com