def put(self, request, pk, format=None): reservation = self.get_object(pk) serializer = ReservationSerializer(reservation, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, req, format=None): fileData = req.FILES['invitationsFile'] if not fileData.name.endswith('.csv'): return Response({"detail": "Not format accepted"}, status=status.HTTP_400_BAD_REQUEST) file_data = fileData.read().decode("utf-8") lines = file_data.split("\n") lst = [] for line in lines: row = line.split(",") if (len(row) == 5): sData = { "firstName": row[0], "lastName": row[1], "startTime": datetime.datetime.strptime(row[2], '%m/%d/%y %I:%M %p'), "endTime": datetime.datetime.strptime(row[3], '%m/%d/%y %I:%M %p'), "seats": row[4] } s = ReservationSerializer(data=sData) if s.is_valid(): s.save() lst.append(s.data) return Response(lst, status=status.HTTP_201_CREATED)
def test_serializer_updates_if_update_data_has_the_same_number_of_guests( self, ): room = MeetingRoom.objects.create(title="Games room") john = User.objects.create(username="******", password="******") peter = User.objects.create(username="******", password="******") zigmas = User.objects.create(username="******", password="******") reservation = Reservation.objects.create( title="Another foosball break", from_date=self.start, to_date=self.end, room=room, creator=john, ) Invitation.objects.create(reservation=reservation, invitee=peter) new_invitation_data = [{"invitee": zigmas}] serializer = ReservationSerializer(instance=reservation) serializer.update_invitation_data(new_invitation_data) updated_invitation_data = reservation.guests.all() new_invitees = [ invitation.invitee for invitation in updated_invitation_data ] self.assertEqual(len(updated_invitation_data), 1) self.assertEqual(new_invitees[0].username, "zigmas")
def test_start_date_should_be_before_end_date(self): reservation = Reservation( first_name='Greg', last_name='Greggie', room_number='28', start_date=timezone.now().date(), end_date=(timezone.now() - timezone.timedelta(minutes=1)).date()) serializer = ReservationSerializer(instance=reservation) serializer = ReservationSerializer(data=serializer.data) self.assertFalse(serializer.is_valid()) self.assertIn('end_date', serializer.errors)
def post(self, request, format=None): data = request.data serializer = ReservationSerializer(data=data) companions = data['companion'] ##validate을 할 때 serializer의 모든 field를 확인하는데 pop을 하면 companion 이 없어지니까 validation_error가 자꾸 뜬것.... if serializer.is_valid(): reservation = serializer.save() for companion in companions: ##대신 여기서 객체로 넣어주는게 맞음 c = User.objects.get(pk=companion) reservation.companion.add(c) reservation.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
class HouseSerializer(serializers.ModelSerializer): #host = serializers.PrimaryKeyRelatedField(source='host.username',queryset=get_user_model().objects.all()) host = UserSerializer(read_only=True) reviews = ReviewSerializer(many=True, read_only=True) #house_img = HouseImageSerializer(many=True,read_only=True) reservations = ReservationSerializer(many=True, read_only=True) class Meta: model = House fields = [ 'id', 'title', 'description', 'cost', 'garage', 'wifi', 'aircondition', 'city', 'country', 'image', 'lon', 'lat', 'av_from', 'av_to', 'host', 'reviews', 'reservations', 'heat', 'area', 'beds', 'bedrooms', 'bathrooms', 'transport_desc', 'house_type', 'people_num', 'people_max', 'rules', 'plus_cost' ] def update(self, instance, validated_data): instance.id = validated_data.get('id', instance.id) instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.cost = validated_data.get('cost', instance.cost) #instance.rooms = validated_data.get('rooms', instance.rooms) instance.garage = validated_data.get('garage', instance.garage) instance.wifi = validated_data.get('wifi', instance.wifi) instance.aircondition = validated_data.get('aircondition', instance.aircondition) instance.city = validated_data.get('city', instance.city) instance.country = validated_data.get('country', instance.country) instance.image = validated_data.get('image', instance.image) instance.lon = validated_data.get('lon', instance.lon) instance.lat = validated_data.get('lat', instance.lat) #instance.host = validated_data.get('host.username',instance.host) #new fields instance.heat = validated_data.get('heat', instance.heat) instance.area = validated_data.get('area', instance.area) instance.beds = validated_data.get('beds', instance.beds) instance.bedrooms = validated_data.get('bedrooms', instance.bedrooms) instance.bathrooms = validated_data.get('bathrooms', instance.bathrooms) instance.transport_desc = validated_data.get('transport_desc', instance.transport_desc) instance.house_type = validated_data.get('house_type', instance.house_type) instance.people_num = validated_data.get('people_num', instance.people_num) instance.people_max = validated_data.get('people_max', instance.people_max) instance.rules = validated_data.get('rules', instance.rules) instance.plus_cost = validated_data.get('plus_cost', instance.plus_cost) instance.av_from = validated_data.get('av_from', instance.av_from) instance.av_to = validated_data.get('av_to', instance.av_to) instance.save() return instance
def get_by_username(self, username): user = User.objects.get(username=username) reservations = Reservation.objects.filter(author=user.id) serializer = ReservationSerializer(reservations, many=True) return JsonResponse(serializer.data, safe=False)
class PaymentSerializer(serializers.ModelSerializer): reservation = ReservationSerializer(read_only=True) class Meta: model = Payment fields = ( 'pk', 'imp_uid', 'merchant_uid', 'pay_method', 'pg_provider', 'pg_tid', 'name', 'amount', 'cancel_amount', 'currency', 'status', 'paid_at', 'failed_at', 'cancelled_at', 'fail_reason', 'cancel_reason', 'buyer_name', 'buyer_email', 'buyer_tel', 'reservation', )
def test_get_valid_single_item(self): response = self.client.get( reverse(self.detail_url_name, kwargs={'pk': 1})) item = Reservation.objects.get(pk=1) serializer = ReservationSerializer(item) self.assertEqual(response.data, serializer.data)
def get(self, request, format=None): order = request.GET.get('order_by') if order: reservations = Reservation.objects.order_by(order).all() else: reservations = Reservation.objects.all() serializer = ReservationSerializer(reservations, many=True) return Response(serializer.data)
def test_search_reservations_by_date_range(self): response = self.client.get(reverse('reservation-list'), { 'start_date_range': '2017-09-10', 'end_date_range': '2017-09-12' }) serializer = ReservationSerializer( [self.reservation1, self.reservation2], many=True) self.assertEqual(serializer.data, response.data)
def test_serializer_updates_if_update_data_has_more_guests(self): room = MeetingRoom.objects.create(title="Games room") john = User.objects.create(username="******", password="******") peter = User.objects.create(username="******", password="******") zigmas = User.objects.create(username="******", password="******") reservation = Reservation.objects.create( title="Another foosball break", from_date=self.start, to_date=self.end, room=room, creator=john, ) new_invitation_data = [{"invitee": zigmas}, {"invitee": peter}] serializer = ReservationSerializer(instance=reservation) serializer.update_invitation_data(new_invitation_data) updated_invitation_data = reservation.guests.all() self.assertEqual(len(updated_invitation_data), 2)
def get(self, request, pk): car = get_object_or_404(Car, id=pk) reservations_set = car.reservation_set.all() reviews_set = car.review_set.all() reservations = ReservationSerializer(reservations_set, many=True).data reviews = ReviewSerializer(reviews_set, many=True).data car_data = CarDetailsSerializer(car, many=False).data for review in reviews: reservation = Reservation.objects.get(pk=review['reservation']) review['reservation'] = ReservationSerializer(reservation, many=False).data renter_id = User.objects.get(pk=review['reservation']['renter_id']) review['reservation']['renter_id'] = OwnerSerializer(renter_id, many=False).data # picturess = GetPicSerializer(car.pictures, many=True).data # raise exceptions.ValidationError(picturess) car_data['reservations'] = reservations car_data['reviews'] = reviews car_data['rating'] = self.get_rating(reviews_set) car_data['times_rented'] = reviews_set.count() return Response(car_data, status=status.HTTP_200_OK)
def get(self, request): reservations = Reservation.objects.all() date = request.query_params.get('date', None) if date: try: year, month, day = date.split('-') except ValueError: return Response( {"error": "Wrong date format, need to be like YYYY-MM-DD"}, status=status.HTTP_400_BAD_REQUEST) reservations = reservations.filter(date__year=year, date__month=month, date__day=day) return Response(ReservationSerializer(reservations, many=True).data, status=status.HTTP_200_OK)
def post(self, request): try: start_year = self.request.data['start_year'] start_month = self.request.data['start_month'] start_day = self.request.data['start_day'] end_year = self.request.data['end_year'] end_month = self.request.data['end_month'] end_day = self.request.data['end_day'] except MultiValueDictKeyError: raise exceptions.ValidationError info = Reservation.objects.filter(information__date__range=[ f'{start_year}-{start_month}-{start_day}', f'{end_year}-{end_month}-{end_day}' ]) filtered_info = info.filter(user=request.user) serializer = ReservationSerializer(filtered_info, many=True) return Response(serializer.data)
def setUp(self): self.start = datetime(2021, 5, 5, 11, 0, 0) self.end = datetime(2021, 5, 5, 10, 0, 0) self.serializer = ReservationSerializer()
def get(self, request, pk, format=None): reservation = self.get_object(pk) serializer = ReservationSerializer(reservation) return Response(serializer.data)
def post(self, request, format=None): user = User.objects.get(username=request.data['username']) reservations = Reservation.objects.filter(reserver=user) ##get 은 하나만, filter 는 여러개 잊지말기 serializer = ReservationSerializer(reservations, many=True) return Response(serializer.data)
def post(self, request, format=None): serializer = ReservationSerializer(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_400_BAD_REQUEST)
def test_get_return_all_items(self): response = self.client.get(reverse(self.list_url_name)) items = Reservation.objects.all() serializer = ReservationSerializer(items, many=True) self.assertEqual(response.data, serializer.data)