[Django]-Custom json response after creating user in Django rest framework

4👍

By default, the ModelViewSet returns the newly created serialized model in response to a POST request.

If you want all requests to have a different structure that the serialized model, check Niranj’s solution. However, if you need a specific response structure for this request only, you will need to override your view’s .create() method:

class UserViewSet(viewsets.ModelViewSet):
    ...

    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)

        # Define how would you like your response data to look like.
        response_data = {
            "success": "True",
            "message": "Successfully sent",
            "user": serializer.data
        }
        return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)
👤iulian

0👍

I guess you need to give metadata on how your our json response must be. Please check this http://www.django-rest-framework.org/api-guide/metadata/ more information

0👍

Use data as dict. and now update it with your user data

data = {
   "success": "True",
   "message": "Successfully sent",
   #serializer.data or anything that return user data dict
   "user": serializer.data
}

Leave a comment