Amir
Amir

Reputation: 8929

Custom json response after creating user in Django rest framework

I am new to django-rest-framework. I am searching for a solution but can't find my straight forward solution and got stuck. Help will be cordially accepted.

I am getting a .json response like this after creating ScreenShotUser model:

{
    "id": 1,
    "name": "amir",
    "age": "30"
}

But I want to get a .json output like below :

 {
   "success": "True",
   "message": "Successfully sent",
   "user": {
     "id": 1,
     "name": "amir",
     "age": "30"
   }
 }

ScreenShotUser.py

class ScreenShotUser(models.Model):
      name = models.CharField(max_length=30)
      age = models.CharField(max_length=30)

ScreenShotUserSerializer.py

ScreenShotUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = ScreenShotUser
        fields = '__all__'

UserViewSet.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = ScreenShotUser.objects.all()
    serializer_class = UserSerializer

I am using django restframework 3.3.2. TIA

Upvotes: 3

Views: 1658

Answers (3)

GrvTyagi
GrvTyagi

Reputation: 4497

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
}

Upvotes: 0

iulian
iulian

Reputation: 5822

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)

Upvotes: 5

Niranj Rajasekaran
Niranj Rajasekaran

Reputation: 778

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

Upvotes: 0

Related Questions