def create(self, request):
        car = request.data
        serializer = CarSerializer(data=car)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(status=status.HTTP_201_CREATED)
Exemple #2
0
    def update(self, request, pk=None):

        user = request.user
        data = request.data

        #get the car to be updated
        car = Car.objects.get(id=pk)

        data['driver_id'] = user.id

        if user.is_driver == 1:

            serializer = CarSerializer(car, data=request.data)

            if serializer.is_valid():

                serializer.save()

                return Response("car details updated successfully",
                                HTTP_200_OK)

            else:
                return Response(serializer.errors, HTTP_400_BAD_REQUEST)

        else:
            return Response('not authorized', HTTP_401_UNAUTHORIZED)
Exemple #3
0
    def create(self, request):

        user = request.user
        data = request.data

        if user.is_driver == 1:

            #add driver_id to the data
            data['driver_id'] = user.id

            print("here is the data")
            print(data)
            print(" ")
            #serialize the data
            serializer = CarSerializer(data=data)

            if serializer.is_valid():

                print(serializer.validated_data)
                serializer.save()
                return Response("car added to database!", HTTP_200_OK)

            else:

                return Response(serializer.errors, HTTP_400_BAD_REQUEST)

        else:
            return Response('user not authorized', HTTP_401_UNAUTHORIZED)
Exemple #4
0
 def put(self, request, id):
     car = self.get_car(id)
     serializer = CarSerializer(instance=car, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response({'error': serializer.errors})
Exemple #5
0
def car_detail(request, pk):
    """
    Get, update, or delete a specific car
    """
    try:
        car = Car.objects.get(pk=pk)
        
    except Car.DoesNotExist:
        return Response(status=HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CarSerializer(car)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = CarSerializer(car, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(
                            serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        car.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
def car_list(request):

    if request.method == 'GET':
        cars = Car.objects.all()
        car_serializer = CarSerializer(cars, many=True)

        return JsonResponse(car_serializer.data, safe=False)

    elif request.method == 'POST':
        car_data = JSONParser().parse(request)
        car_serializer = CarSerializer(data=car_data)

        if car_serializer.is_valid():

            if Car.objects.filter(name=car_data['name']).count() != 0:
                return JsonResponse({"Error": "Car already exist"})

            car_serializer.save()
            return JsonResponse(car_serializer.data,
                                status=status.HTTP_201_CREATED)

        return JsonResponse(car_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'PUT':
        details = JSONParser().parse(request)
        car_1 = Car.objects.get(name=details['name_1'])
        car_2 = Car.objects.get(name=details['name_2'])
        temp = car_1.name
        car_1.name = car_2.name
        car_2.name = temp
        car_1.save()
        car_2.save()
        return JsonResponse({"Success": "Cars have been swapped"})
Exemple #7
0
 def put(self, request, pk):
     seller = self.get_object(pk)
     serializer = CarSerializer(instance=seller, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors,
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #8
0
 def post(self, request, id):
     brand = self.get_brand(id)
     profile = Profile.objects.get(user=self.request.user)
     serializer = CarSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save(brand=brand, author_id=profile.id)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response({'error': serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    def create(self, request):
        order = request.data
        order["create_date"] = date.today()
        car_id = order["car"]
        user_id = order["user"]
        seller_id = order["seller"]

        if user_id is None or car_id is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # update car
        car = Car.objects.all().get(id=car_id)
        if car is None:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if car.status == 1:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # update user
        user = User.objects.all().get(id=user_id)
        if user is None:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if user.balance < car.price:
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)

        car.status = 1
        serializer_car = CarSerializer(car, data={}, partial=True)
        serializer_car.is_valid(raise_exception=True)
        serializer_car.save()

        # user.balance = user.balance - car.price
        # serializer_user = UserSerializer(user, data={}, partial=True)
        # serializer_user.is_valid(raise_exception=True)
        # serializer_user.save()

        serializer = OrderSerializer(data=order)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_201_CREATED)
Exemple #10
0
def car_list(request):
    """
    List all cars or create a new car
    """
    if request.method == 'GET':
        cars = Car.objects.all()
        serializer = CarSerializer(cars, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = CarSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #11
0
def car_list(request):
    """
    List all cars or create a new car
    """
    if request.method == 'GET':
        cars = Car.objects.all()
        serializer = CarSerializer(cars, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = CarSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,
                            status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemple #12
0
    def post(self, request, *args, **kwargs):
        serialization = CarSerializer(data=request.data)

        if serialization.is_valid():
            company_name_capitalize = request.data['make'].capitalize()
            company = Company.objects.filter(
                make=company_name_capitalize).first()

            if company:
                car = Car.objects.filter(make=company.id).filter(
                    model=request.data['model']).first()

            if company and car:
                return Response('Already exist',
                                status=status.HTTP_400_BAD_REQUEST)

            else:
                try:
                    json_data = self.request_to_external_car_api(
                        request.data['make'])
                except:
                    return Response('External API problem',
                                    status=status.HTTP_400_BAD_REQUEST)

                if json_data['Count'] > 0:
                    for model in json_data['Results']:
                        if model['Model_Name'] == request.data['model']:
                            make = Company.objects.get_or_create(
                                make=request.data['make'].capitalize())
                            Car.objects.create(make=make[0],
                                               model=request.data['model'])
                            return Response(status=status.HTTP_201_CREATED)
                    return Response('Model not found in API',
                                    status=status.HTTP_400_BAD_REQUEST)

                else:
                    return Response('Model not found in API',
                                    status=status.HTTP_400_BAD_REQUEST)

        return Response(serialization.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Exemple #13
0
def cars(request, format=None):
    if request.method == "GET":
        cars = Car.objects.all()
        if not cars:
            return Response({"Message": "Empty database"})
        serializer = CarSerializer(cars, many=True)
        return Response(serializer.data)
    if request.method == "POST":
        url = Car.url
        post_fields = {"format": "json"}
        serializer = CarSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {"Error": "Fields not valid. Check the request body."})
        else:
            try:
                # <---------- Connect to external API --------------->
                make = request.data.get("make")
                r_make = requests.get(url + make, params=post_fields)
                r_make.raise_for_status()
            # Can handle HTTPError, timeout, network connection separately if needed
            except Exception as e:
                return Response({"Error": e.args[0]},
                                status=r_make.status_code)
            # <---------- Search through the results for a match --------------->
            for item in r_make.json()["Results"]:
                if request.data.get("model") in item.values():
                    # <---------- Save to database --------------->
                    serializer.save()
                    # print("saving")
                    return Response(serializer.data,
                                    status=status.HTTP_201_CREATED)
            # <---------- In case search was not matched --------------->
            return Response(
                {"Error": "Car was not found, can not add to database"},
                status=status.HTTP_404_NOT_FOUND,
            )
Exemple #14
0
def car_detail(request, pk):
    """
    Get, update, or delete a specific car
    """
    try:
        car = Car.objects.get(pk=pk)

    except Car.DoesNotExist:
        return Response(status=HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CarSerializer(car)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = CarSerializer(car, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        car.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #15
0
 def test_valid_data(self):
     serializer = CarSerializer(data=self.serializer_data)
     self.assertTrue(serializer.is_valid())
     self.assertFalse(serializer.errors)
Exemple #16
0
 def test_too_long_model(self):
     self.serializer_data["model"] = "x" * 256
     serializer = CarSerializer(data=self.serializer_data)
     self.assertEqual(serializer.is_valid(), False)
     self.assertCountEqual(serializer.errors.keys(), ["model"])