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 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)
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)
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})
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)
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 list(self, request): """ GET (ALL) """ city = self.request.query_params.get('city', None) date_start = self.request.query_params.get('date_start', None) date_end = self.request.query_params.get('date_end', None) orders_db = Order.objects.filter( Q(date_start__range=(date_start, date_end)) | Q(date_end__range=(date_start, date_end))) if(date_start == None or date_end == None): cars_db = Car.objects.all() else: cars_db = Car.objects.exclude( car_order__in=orders_db) # cars_db = Car.objects.filter( # car_order__in=orders_db) | Car.objects.filter(car_order=None) if(city): cars_db = cars_db.filter(city=city) cars_serializer = CarSerializer(cars_db, many=True) return Response(cars_serializer.data)
def car_details(request, pk): try: car = Car.objects.get(id=pk) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ser = CarSerializer(car) print(ser.data) return Response(ser.data, status=status.HTTP_200_OK)
def car_by_model(request, pk): try: model = Model.objects.get(id=pk) except Exception as e: return Response({'error': str(e)}) serializer = CarSerializer(model.cars.all(), many=True) return Response(serializer.data)
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)
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"})
def cars_of_basket(request): try: basket = request.user.basket except Basket.DoesNotExist as e: return Response({'error': str(e)}) if request.method == 'GET': print(basket.cars) cars = basket.cars serializer = CarSerializer(cars, many=True) return Response(serializer.data)
def test_serializer_response(self): serializer_response = client.get(reverse("api:car_list")) cars = Car.objects.all() serializer = CarSerializer(cars, many=True) self.assertTrue('make' in serializer_response.data[0]) self.assertTrue('id' in serializer_response.data[0]) self.assertTrue('model' in serializer_response.data[0]) self.assertTrue('make' in serializer.data[0]) self.assertTrue('id' in serializer.data[0]) self.assertTrue('model' in serializer.data[0])
def setUp(self): self.company = Company.objects.create(make='Honda') self.car = Car.objects.create(model='Accord', make=self.company) self.serializer_data = {"make": "Volkswagen", "model": "Golf"} Rate.objects.create(car=self.car, rating=5) Rate.objects.create(car=self.car, rating=1) self.serialized_model = CarSerializer(instance=self.car)
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)
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)
def retrieve(self, request, car_id=None): """ GET (ONE) """ # Dirty version # cars_db = Car.objects.all() # car = get_object_or_404(cars_db, pk=car_id) # Clean Version car = get_object_or_404(Car, pk=car_id) car_serializer = CarSerializer(car) return Response(car_serializer.data)
def destroy(self, request, car_id=None): """ DELETE """ # Dirty version # cars_db = Car.objects.all() # car = get_object_or_404(cars_db, pk=car_id) # Clean Version car = get_object_or_404(Car, pk=car_id) car.delete() car_serializer = CarSerializer(car) return Response(car_serializer.data, status=status.HTTP_200_OK)
def list(self, request): brand = request.GET.get("brand") start_price = request.GET.get("startPrice") end_price = request.GET.get("endPrice") keyword = request.GET.get("keyword") cars = Car.objects.all() cars = cars.filter(status=0) if brand: cars = cars.filter(brand=brand) if start_price: cars = cars.filter(price__gte=start_price) if end_price: cars = cars.filter(price__lte=end_price) if keyword: cars = cars.filter( Q(name__contains=keyword) | Q(price__contains=keyword) | Q(brand__contains=keyword) | Q(brand__contains=keyword)) serializer = CarSerializer(cars, many=True) return Response(serializer.data)
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, )
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 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)
def get(self, request, id): profile = self.get_profile(id) cars = profile.cars.all() serializer = CarSerializer(cars, many=True) return Response(serializer.data)
def get(self, request, id): car = self.get_car(id) serializer = CarSerializer(car) return Response(serializer.data)
def get(self, request, pk): seller = self.get_object(pk) serializer = CarSerializer(seller) return Response(serializer.data)
def get(self, request): cars_list = Car.objects.all() serializer = CarSerializer(cars_list, many=True) return Response(serializer.data)
def retrieve(self, request, pk=None): car = Car.objects.all().get(id=pk) serializer = CarSerializer(car) return Response(serializer.data)
def get(self, request, *args, **kwargs): car = Car.objects.get(pk=kwargs['pk']) serializer = CarSerializer(car, many=False) return Response({"car": serializer.data})
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"])
def insert_car(car): data = CarSerializer(instance=car).data manufacturer = Manufacturer.objects.get(id=car.manufacturer_id) data['manufacturer'] = manufacturer.name collection.update_one(data, {'$set': data}, upsert=True)
def test_valid_data(self): serializer = CarSerializer(data=self.serializer_data) self.assertTrue(serializer.is_valid()) self.assertFalse(serializer.errors)