Reputation: 1655
I'm trying to override the response message(return data) of the serializer. Below is my sample code.
models.py
from django.db import models
class MyModel(models.Model):
name = models.charField()
email = models.EmailField()
phone = models.charField()
serializer.py
from rest_framework import serializers
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'name', 'email', 'phone')
def validate(self, data):
'''
Some validation here
'''
return data
views.py
from rest_framework import generics
class MyModelList(generics.ListCreateAPIView):
queryset = MyModel.objects.all().order_by('-id')
serializer_class = MyModelSerializer
Here, when I try to post the data, the serializer return the response in the json format like this
{
'id': 2,
'name': 'myname',
'email': '[email protected]',
'phone': 8569874587,
}
But I want to return the custom json response like this if the post is success.
{
'success' : 'data posted successfully',
}
Guys how can I override this for the custom message, please help me for this, it will be very great-full, Thanks in advance.
Upvotes: 2
Views: 1571
Reputation: 489
Overwrite the create method of ListCreateAPIView
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": "Data posted successfully"},
status=status.HTTP_201_CREATED,
headers=headers)
Upvotes: 3