def post(self, request):
     data = request.data
     serializer = PostSerializer(data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=201)
     return Response(serializer.errors, status=400)
 def put(self, request, id):
     data = request.data
     instance = self.get_object(id)
     serializer = PostSerializer(instance, data=data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=200)
     return Response(serializer.errors, status=400)
def posts(request):
    if request.method == 'GET':
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)

        return JsonResponse(serializer.data, safe=False)

    elif request.method == "POST":
        json_parser = JSONParser()
        data = json_parser.parse(request)
        serializer = PostSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
def post_detail2(request, id):
    try:
        instance = Post.objects.get(id=id)
    except Post.DoesNotExist as e:
        return JsonResponse({'error': "given post object does not found"},
                            status=404)

    if request.method == 'GET':
        serializer = PostSerializer(instance)
        return JsonResponse(serializer.data)

    elif request.method == "PUT":
        json_parser = JSONParser()
        data = json_parser.parse(request)
        serializer = PostSerializer(instance, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=200)
        return JsonResponse(serializer.errors, status=400)
    elif request.method == "DELETE":
        instance.delete()
        return HttpResponse(status=204)