Ejemplo n.º 1
0
 def patch(self, request, pk):
     place = get_object_or_404(Place, pk=pk)
     serializer = PlaceSerializer(place, data=request.data, partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
def place_detail(request, cat, pk):
    """
    functions retrieves, updates or deletes a place.
    """

    try:
        category = Category.objects.get(pk=cat)
    except Category.DoesNotExist:
        return HttpResponse(status=404)

    try:
        place = Place.objects.get(category=category, pk=pk)
    except Place.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = PlaceSerializer(place)
        return JSONResponse(serializer.data)

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

    elif request.method == 'DELETE':
        place.delete()
        return HttpResponse(status=204)
class RouteSerializer(serializers.ModelSerializer):

    place_origin = PlaceSerializer(many=False, read_only=True)
    place_destination = PlaceSerializer(many=False, read_only=True)

    class Meta:
        model = Route
        fields = ["id", "place_origin", "place_destination"]
Ejemplo n.º 4
0
class TripSerializer(serializers.HyperlinkedModelSerializer):
    origin_id = serializers.PrimaryKeyRelatedField(
        queryset=Place.objects.all(), source='origin', write_only=True)

    origin = PlaceSerializer(read_only=True)

    destination_id = serializers.PrimaryKeyRelatedField(
        queryset=Place.objects.all(), source='destination', write_only=True)
    destination = PlaceSerializer(read_only=True)

    vehicle_id = UserFilteredPrimaryKeyRelatedField(queryset=Vehicle.objects,
                                                    source='vehicle',
                                                    write_only=True)

    vehicle = VehicleSerializer(read_only=True)

    driver = UserSerializer(source='user', read_only=True)

    def validate_trip_date(self, value):
        if value < date.today():
            raise serializers.ValidationError(
                'Trip date cannot be in the past')
        return value

    def validate(self, data):
        if data['origin'] == data['destination']:
            raise serializers.ValidationError(
                'Origin and destination cannot be the same')

        return data

    class Meta:
        model = Trip
        fields = [
            'id',
            'url',
            'trip_date',
            'num_seats',
            'origin_id',
            'origin',
            'destination_id',
            'destination',
            'vehicle_id',
            'vehicle',
            'driver',
        ]
Ejemplo n.º 5
0
    def places(self, request, *args, **kwargs):
        snippet = self.get_object()
        lat = request.query_params['lat']
        lng = request.query_params['lng']

        userId = kwargs.get("id")
        listPlaces = []

        user = User.objects(id=userId).get()
        userTypes = user.types
        if not userTypes:
            userTypes = [
                '594c36a033cbb6eed6f364e6', '594c36b233cbb6eed6f364f2',
                '594c368633cbb6eed6f364da', '594c4a504362de3d8fae464f',
                '5956fee67d2bf938c292e0bc'
            ]

        places = Place.objects(Q(loc__near=[float(lat), float(lng)]))

        for type in userTypes:
            typeName = Category.objects(id=type).get().name

            for place in places:
                if typeName in place.types:

                    # Rating place according to twitter
                    twitterRating = len(
                        Tweet.objects(text__contains=place.name))
                    place.twitter_rating = twitterRating

                    #Rating place according to user
                    userRating = RatedPlace.objects(
                        Q(user_id__exact=userId) & Q(place_id__exact=place.id))

                    if userRating:

                        rating = userRating.order_by('-id').first().rating
                    else:
                        rating = ''
                    place.user_rating = rating

                    #Adding places to list of recommended places
                    listPlaces.append(place)

                    # Sort the list according to twitter rated
                    listPlaces.sort(key=lambda x: x.twitter_rating,
                                    reverse=True)

                    # Sort the list according to user rated
                    listPlaces.sort(key=lambda x: x.user_rating, reverse=True)

        serializer = PlaceSerializer(listPlaces[:20], many=True)

        return Response(serializer.data)
Ejemplo n.º 6
0
def place_list(request, pk):
    """
    List all code places, or create a new place.
    """
    try:
        category = Category.objects.get(pk=pk)
    except Category.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        places = Place.objects.filter(category=category)	
        serializer = PlaceSerializer(places, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PlaceSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
Ejemplo n.º 7
0
    def test_endpoint_list(self):
        url = reverse('place-list')
        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, 200)
        place_list = json.loads(response.content)

        for place in place_list:
            id = place.get('id')
            place_model = PlaceSerializer(model_to_dict(Place.objects.get(id=id))).data
            print(place)
            print(place_model)
            print("-------------")
            self.assertEqual(place, place_model)
Ejemplo n.º 8
0
class ArticleListSerializer(serializers.ModelSerializer):
    place = PlaceSerializer(read_only=True)
    main_image = ImageSerializer(read_only=True)

    class Meta:
        model = Article
        exclude = ['content', 'images']

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['type_title'] = instance.get_type_display()
        ret['place_id'] = instance.place_id
        return ret
Ejemplo n.º 9
0
class ArticleDetailsSerializer(serializers.ModelSerializer):
    place = PlaceSerializer(read_only=True)
    images = ImageSerializer(read_only=True, many=True)

    class Meta:
        model = Article
        fields = '__all__'

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['type_title'] = instance.get_type_display()
        ret['place_id'] = instance.place_id
        return ret
Ejemplo n.º 10
0
 def random(self, request, *args, **kwargs):
     count = Place.objects.count()
     random = randint(0, count - 10)
     places = Place.objects(
         Q(types__contains="restaurant") | Q(types__contains="bar")
         | Q(types__contains="food") | Q(types__contains="bakery")
         | Q(types__contains="cafe") | Q(types__contains="casino")
         | Q(types__contains="convenience_store")
         | Q(types__contains="meal_delivery")
         | Q(types__contains="make_takeaway")
         | Q(types__contains="nightclub")
         | Q(types__contains="shopping_mall")).limit(10).skip(random)
     serializer = PlaceSerializer(places, many=True)
     return Response(serializer.data)
Ejemplo n.º 11
0
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
    place = PlaceSerializer(many=False)

    class Meta:
        fields = "__all__"
        model = Institution
Ejemplo n.º 12
0
 def get(self, request):
     places = Place.objects.all()
     serializer = PlaceSerializer(places, many=True)
     return Response(serializer.data)
Ejemplo n.º 13
0
 def get(self, request, pk):
     place = get_object_or_404(Place, pk=pk)
     serializer = PlaceSerializer(place)
     return Response(serializer.data)
Ejemplo n.º 14
0
 def post(self, request):
     serializer = PlaceSerializer(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)
Ejemplo n.º 15
0
 def get(self, request, pk, format=None):
     place = self.get_object(pk)
     place = PlaceSerializer(place)
     return Response(place.data)