Hi, I have a problem saving data.
I receive the message as if they are saved successfully but they are not saved in the database …
This is the code I wrote
APi VIEW
class CreateApiView(APIView):
def post(self, request):
data_serializer = ProductsSerializer(data=self.request.POST)
if data_serializer.is_valid():
data_serializer.save()
return Response(data={'message': 'Succes'}, status=200)
Serializer
class ProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('id', 'title', 'description')
url
urlpatterns = [
url(r'^api/test', views.CreateApiView.as_view(), name='post')
]
Hi @Dani-D99,
Your view returns a success message for all cases except for an exception. Try changing it so it will return an error response:
class CreateApiView(APIView):
def post(self, request):
data_serializer = ProductsSerializer(data=self.request.POST)
if data_serializer.is_valid():
data_serializer.save()
return Response(data={'message': 'Succes'}, status=200)
# Need to format the validation error somehow to inform the client what's wrong.
return Response(data={'message': 'Error'}, status=400)
Or use DRF’s ability to format a validation exception as an error:
class CreateApiView(APIView):
def post(self, request):
data_serializer = ProductsSerializer(data=self.request.POST)
data_serializer.is_valid(raise_exception=True)
data_serializer.save()
return Response(data={'message': 'Succes'}, status=200)
You can read more about DRF’s validation here.