From 76392635c419a1a1d79b3535c10523d128ed69c1 Mon Sep 17 00:00:00 2001 From: Simon Luijk Date: Thu, 2 Jan 2014 11:41:21 +0100 Subject: [PATCH] Add hook for response data in Create and Update mixins Warning: This is to start a discussion and has not been tested. Our use case for this is to remove a field from the output. The previous solutions also remove the field from the Browsable API after a PUT request!, where not consistent across POST and PUT requests, or increased boiler plate. But this could also be used to return a simple status message rather than an object or a more complex object. Maybe the object should also be passed to the hooks? It might also be better to have one hook (Where to implement?) self.request.method could be used to distinguish between POST/PUT. The hooks could return the response instead, giving control over the status code and headers too. --- rest_framework/mixins.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 43950c4bf..cc9db9dd9 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -53,7 +53,8 @@ class CreateModelMixin(object): self.object = serializer.save(force_insert=True) self.post_save(self.object, created=True) headers = self.get_success_headers(serializer.data) - return Response(serializer.data, status=status.HTTP_201_CREATED, + data = self.get_create_response_data(serializer) + return Response(data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -64,6 +65,9 @@ class CreateModelMixin(object): except (TypeError, KeyError): return {} + def get_create_response_data(self, serializer): + return serializer.data + class ListModelMixin(object): """ @@ -136,7 +140,8 @@ class UpdateModelMixin(object): return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST) self.object = serializer.save(**save_kwargs) self.post_save(self.object, created=created) - return Response(serializer.data, status=success_status_code) + data = self.get_update_response_data(serializer) + return Response(data, status=success_status_code) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -159,6 +164,9 @@ class UpdateModelMixin(object): # return a 404 response. raise + def get_update_response_data(self, serializer): + return serializer.data + def pre_save(self, obj): """ Set any attributes on the object that are implicit in the request.