Пример #1
0
    def _update_trip(self, data):
        instance = Trip.objects.get(id=data.get('id'))

        serializer = TripSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        return serializer.update(instance, serializer.validated_data)
Пример #2
0
 def getMyTrips(self, request):
     myTrips = []
     user = self.request.user
     for trip in Trip.objects.all():
         print(TripSerializer(trip).data)
         if user.has_perm('view_trip', trip):
             myTrips.append(TripSerializer(trip).data)
     return Response(myTrips)
Пример #3
0
 def post(self, request: Request):
     serializer = TripSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     trip = serializer.save()
     calculate_price(trip.user_id, start_of_week(trip.start_time),
                     end_of_week(trip.end_time))
     print(trip)
     return Response(data=serializer.data)
Пример #4
0
 def put(self, request, pk, format='json'):
     trip = self.get_object(pk)
     serializer = TripSerializer(trip, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return JsonResponse(serializer.data, safe=False)
     return JsonResponse(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST,
                         safe=False)
Пример #5
0
 def _update_trip(self, data):
     # Retrieve the Trip obj by ID
     instance = Trip.objects.get(id=data.get('id'))
     # Serialize the Trip data with update
     serializer = TripSerializer(data=data)
     # Ensure the serialized data is valid according to the model fields
     serializer.is_valid(raise_exception=True)
     # Use built-in update() passing in the Trip obj (instance) and the serializer data
     return serializer.update(instance, serializer.validated_data)
Пример #6
0
 def post(self, request, format='json'):
     serializer = TripSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return JsonResponse(serializer.data,
                             status=status.HTTP_201_CREATED,
                             safe=False)
     return JsonResponse(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST,
                         safe=False)
Пример #7
0
def trip_detail(request, pk):
    try:
        trip = Trip.objects.get(pk=pk)
    except Trip.DoesNotExist:
        return JsonResponse({'message': 'trip no  existe'},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        trip_serializer = TripSerializer(trip)
        return JsonResponse(trip_serializer.data)

    elif request.method == 'PUT':
        trip_data = JSONParser().parse(request)
        trip_serializer = TripSerializer(trip, data=trip_data)
        if trip_serializer.is_valid():
            trip_serializer.save()
            return JsonResponse(trip_serializer.data)
        return JsonResponse(trip_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        trip.delete()
        return JsonResponse(
            {'message': 'trip fue eliminado satisfactoriamente!'},
            status=status.HTTP_204_NO_CONTENT)
Пример #8
0
def trip_total_viajes_ciudad(request, pk):
    try:
        #trip = Trip.objects.get(pk=pk)
        count = Trip.objects.all().filter(cityname='Bogotá').count()

    except Trip.DoesNotExist:
        return JsonResponse({'message': 'La ciudad no existe'},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        trip_serializer = TripSerializer(trip)
        return JsonResponse({'message': 'Existen {} Viajes!'.format(count)},
                            status=status.HTTP_204_NO_CONTENT)

    elif request.method == 'PUT':
        trip_data = JSONParser().parse(request)
        trip_serializer = TripSerializer(trip, data=trip_data)
        if trip_serializer.is_valid():
            trip_serializer.save()
            return JsonResponse(trip_serializer.data)
        return JsonResponse(trip_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        trip.delete()
        return JsonResponse({'message': 'trip borrado exitosamente!'},
                            status=status.HTTP_204_NO_CONTENT)
Пример #9
0
def test_trip_serializer():
    trip = Trip.objects.create(
        name='trip-1',
        slug='trip-1',
        date_from=date.today() - timedelta(5),
        date_to=date.today(),
        description='This is description',
    )
    data = TripSerializer(trip).data
    assert list(data.keys()) == [
        'id',
        'name',
        'created_at',
        'slug',
        'date_from',
        'date_to',
        'description',
    ]
Пример #10
0
 def invite(self, request, pk=None):
     trip = Trip.objects.get(pk=pk)
     email = request.data['email']
     user = User.objects.filter(email=email).first()
     if user:
         trip.members.add(user)
         serializer = TripSerializer(trip)
         return Response(serializer.data)
     else:
         return Response('user not found')
Пример #11
0
    def get(self, request: Request):
        user_id = request.query_params.get('user_id')

        # date = datetime.today()-timedelta(days=2)
        # calculate_price(user_id, start_of_week(date), end_of_week(date))

        trips = Trip.objects.all().filter(
            user_id__exact=user_id).order_by('-start_time')
        serializer = TripSerializer(instance=trips, many=True)
        return Response(data=serializer.data)
Пример #12
0
def trip_detail(request, pk):
    try:
        trip = Trip.objects.get(pk=pk)
    except Trip.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = TripSerializer(trip)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = TripSerializer(trip, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        trip.delete()
        return HttpResponse(status=204)
Пример #13
0
def trip_total_viajes(request):
    if request.method == 'GET':
        trips = Trip.objects.all()
        count = Trip.objects.count()

        start = request.GET.get('start', None)
        if start is not None:
            trips = trips.filter(start__icontains=start)

        trips_serializer = TripSerializer(trips, many=True)
        return JsonResponse({'message': 'Existen {} Viajes!'.format(count)},
                            status=status.HTTP_204_NO_CONTENT)
Пример #14
0
def trip_list(request):
    if request.method == 'GET':
        trips = Trip.objects.all()

        start = request.GET.get('start', None)
        if start is not None:
            trips = trips.filter(start__icontains=start)

        trips_serializer = TripSerializer(trips, many=True)
        return JsonResponse(trips_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    elif request.method == 'POST':
        trip_data = JSONParser().parse(request)
        trip_serializer = TripSerializer(data=trip_data)
        if trip_serializer.is_valid():
            trip_serializer.save()
            return JsonResponse(trip_serializer.data,
                                status=status.HTTP_201_CREATED)
        return JsonResponse(trip_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        count = Trip.objects.all().delete()
        return JsonResponse(
            {
                'message':
                '{} Viaje  fué eliminiado satisfactoriamente!'.format(count[0])
            },
            status=status.HTTP_204_NO_CONTENT)
Пример #15
0
class AccountSerializer(ModelSerializer):
    password = CharField(write_only=True)
    trips = TripSerializer(many=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'created_at', 'updated_at', 'password',
                  'trips')
        read_only_fields = (
            'created_at',
            'updated_at',
        )

        def create(self, data):
            """
            Create a new Account.
            """
            return Account.objects.create(**data)
Пример #16
0
    def plinit(self, request, pk=None):
        trip = Trip.objects.get(pk=pk)
        plans = trip.plans.order_by('?').all()
        duration = trip.duration
        plans_per_day = int(len(plans) / duration)
        for i, day in enumerate(trip.days.all()):
            start = i * plans_per_day
            end = i * plans_per_day + plans_per_day
            for j, plan in enumerate(plans[start:end]):
                plan.day = day
                plan.order = j + 1
                plan.save()

        first_day = trip.days.first()
        max_order = first_day.plans.order_by('order').first().order
        for i, plan in enumerate(trip.plans.filter(day__isnull=True)):
            plan.day = first_day
            plan.order = max_order + i + 1
            plan.save()

        serializer = TripSerializer(trip)
        return Response(serializer.data)
Пример #17
0
class BookingSerializer(serializers.ModelSerializer):
    user_id = UserSerializer(read_only=True)
    trip_detail = serializers.IntegerField(write_only=True)
    trip_id = TripSerializer(read_only=True)
    bus_id = BusSerializer(read_only=True)

    class Meta:
        model = Booking
        fields = [
            'booking_number', 'user_id', 'trip_id', 'bus_id', 'trip_detail'
        ]
        read_only_fields = ('created_at', 'booking_number')

    def create(self, validate_data):
        """ creates a new booking list and returns the serialized data"""

        user = self.context['user']
        # Check if trip exists
        get_trip = Trip.objects.get(pk=validate_data['trip_detail'])
        book_trip = Booking.objects.create(user_id=user,
                                           trip_id=get_trip,
                                           bus_id=get_trip.bus_id)
        return book_trip
Пример #18
0
 def _create_trip(self, data):
     serializer = TripSerializer(data=data)
     serializer.is_valid(raise_exception=True)
     return serializer.create(serializer.validated_data)
Пример #19
0
 def _create_trip(self, content):
     serializer = TripSerializer(data=content)
     serializer.is_valid(raise_exception=True)
     trip = serializer.create(serializer.validated_data)
     return trip
Пример #20
0
 def _update_trip(self, content):
     instance = Trip.objects.get(id=content.get('id'))
     serializer = TripSerializer(data=content)
     serializer.is_valid(raise_exception=True)
     trip = serializer.update(instance, serializer.validated_data)
     return trip
Пример #21
0
 def get(self, request, pk, format='json'):
     trip = self.get_object(pk)
     serializer = TripSerializer(trip)
     return JsonResponse(serializer.data, safe=False)
Пример #22
0
 def get(self, request, format='json'):
     # current_user = request.user
     # TODO: get trip by user
     trips = Trip.objects.all()
     serializer = TripSerializer(trips, many=True)
     return JsonResponse(serializer.data, safe=False)