1

The problem is create function is not calling and simply returning validation Boolean value whether its true or false. Please note: Validation part is working fine.

Code as follows:

Views.py

class TestAPI(APIView):
    serializer_request = TestAPISerializer

    def post(self,request):     
        obj = self.serializer_request(data=request.data)
        print obj.is_valid()
        if obj.is_valid():
            obj.save()
            return Response(status=status.HTTP_200_OK)
        else:
            return Response(request_for_demo_ser.errors, status=status.HTTP_400_BAD_REQUEST)

Serializers.py

class TestAPISerializer(serializers.ModelSerializer):
    class Meta:
        model = TestDemo
        fields = ('name')

    # THIS FUNCTION IS NOT AT ALL CALLING. 
    def create(self, validated_data):
        name = validated_data['name'] 
        return TestDemo.objects.create(name=name)

1 Answer 1

4

You forgot save.

obj = self.serializer_request(data=request.data)
print obj.is_valid()
if obj.is_valid():        
    obj.save()  # add this line
    # Change code to 201
    return Response(status=status.HTTP_201_CREATED)
    # return Response(status=status.HTTP_200_OK)
Sign up to request clarification or add additional context in comments.

4 Comments

hi, sorry I was missed the save statement..now the question is updated
isn't function not calling now?
Great !! sorry for the delay. I was used save method before, at that time its was not worked. but now, it is worked properly !! One quick question, why we need save method explicitly in views.py? can't we save in serializer.py or models.py ?
We can decide about save in view only. If data valid and user has permission to save, we'll call save method, in other case we don't save and send message to user. This pattern named MVC. You can read more in wiki en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller P.S.: Sorry for my English

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.