Example #1
0
 def test_required_fields(self, field):
     data = self._default_review_data()
     del data[field]
     serializer = ReviewSerializer(data=data)
     serializer.is_valid()
     self.assertTrue(
         _('This field is required.') in serializer.errors.get(field))
Example #2
0
 def test_submission_date_is_automatically_setted_on_create(self):
     data = self._default_review_data()
     serializer = ReviewSerializer(data=data)
     serializer.is_valid()
     instance = serializer.save(ip_address=self.faker.ipv4(),
                                reviewer=self._user_recipe.make())
     self.assertEquals(instance.submission_date, date.today())
Example #3
0
 def test_review_update_data_company_if_the_id_company_exists(self):
     company = self._company_recipe.make()
     data = self._default_review_data(
         company__company_id=company.company_id, company__name='new name')
     serializer = ReviewSerializer(data=data)
     serializer.is_valid()
     review = serializer.save(ip_address=self.faker.ipv4(),
                              reviewer=self._user_recipe.make())
     self.assertEquals(review.company.name, 'new name')
Example #4
0
def api_insert_review_view(request, **kwargs):
    """
	"author" : "author_name",
	"rating" : "1",
	"weight_score" : "1",
	"text" : "content",
	"restaurant_id" : "1",
	"review_count" : "30",
	"source" : "google",
	"category" : "Pizza",
	"country" : "United States",
	"state" :"GA",
	"created_date" : "2021-01-18"
	"""
    if request.method == 'POST':
        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            # TODO: check if request missing restaurant id
            try:
                res_obj = Restaurant.objects.get(
                    res_id=request.data['restaurant_id'])
            except Restaurant.DoesNotExist:
                res_obj = Restaurant(res_id=request.data['restaurant_id'],
                                     name='',
                                     number_review=0)
                res_obj.save()

            review = res_obj.res_review.create(
                author=serializer.data['author'],
                rating=serializer.data['rating'],
                weight_score=serializer.data['weight_score'],
                text=serializer.data['text'],
                review_count=serializer.data['review_count'],
                source=serializer.data['source'],
                category=serializer.data['category'],
                country=serializer.data['country'],
                state=serializer.data['state'],
                created_date=serializer.data['created_date'])
            review.save()

            res_obj.number_review = int(res_obj.number_review) + 1
            res_obj.save()
            data = {'message': 'Success'}
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)
Example #5
0
 def get(self, request, id, *args, **kwargs):
     # Checking if the user is authenticated
     if request.user.is_authenticated():
         # Getting the review by ID
         review = ReviewController.GetReviewByID(ID=id)
         # Checking if the review is empty
         if review is not None:
             # Returning the response with the review details
             return JsonResponse({
                 'Review':
                 ReviewSerializer(review).data,
                 'Rating':
                 RatingController.GetRating(Person=request.user,
                                            Review=review),
                 'TopicList':
                 ReviewTopicController.GetTopics(Review=review),
                 'MaxRating':
                 5
             })
         else:
             # Returning the response with unable to find the review
             return JsonResponse({'Review': None, 'MaxRating': 5})
     else:
         # Returning the response with unable to find the review
         return JsonResponse({'Review': None, 'MaxRating': 5})
Example #6
0
 def test_reviewer_list_his_reviews(self):
     self.authenticate()
     review = self._review_recipe.make()
     response = self.client.get(self.URL)
     self.assertEquals(
         ReviewSerializer(review).to_representation(review),
         response.json()[0])
class UserSerializer(serializers.ModelSerializer):
    owner_user = ReviewSerializer(many=True, read_only=True)
    bookmarks = UserBookMarkSerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = (
            'id',
            'username',
            'password',
            'owner_user',
            'bookmarks',
        )

        extra_kwargs = {
            "password": {"write_only": True},
        }

    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance
Example #8
0
File: views.py Project: 19andt/test
    def get(self, request, *args, **kwargs):
        # Checking if user is authenticated
        if request.user.is_authenticated():
            # Getting the new subscription count
            observers = []

            for item in SubscriptionController.GetObservers(request.user):
                if item.timestamp > request.user.last_login:
                    observers.append(SubscriptionSerializer(item).data)
            # Getting the new review count
            reviews = []

            for item in ReviewController.ReviewsForUser(request.user):
                if item.created > request.user.last_login and item.added_by != request.user:
                    reviews.append({
                        'review':
                        ReviewSerializer(item).data,
                        'topic_list':
                        ReviewTopicController.GetTopics(item)
                    })

            # Returning the response with reviews and subscription list
            return JsonResponse({
                'Reviews': reviews,
                'Observers': observers,
                'UserAuthenticated': True
            })
        else:
            # User is not authenticated
            return JsonResponse({'UserAuthenticated': False})
Example #9
0
 def get_rating(self, obj):
     average = 0.0
     reviews = ReviewSerializer(obj.items_owner, many=True).data
     if len(reviews) > 0:
         for item in reviews:
             average += item['rating']
         average /= len(reviews)
     return average
 def list(self, request):
     '''
     Return the list of Reviews for the user authenticated by token
     '''
     reviwer = Token.objects.get(user=request.user)
     queryset = Review.objects.filter(
         reviewer=reviwer).order_by('submission_date')
     serializer = ReviewSerializer(queryset, many=True)
     return Response(serializer.data)
Example #11
0
    def review(self, request, *args, **kwargs):
        instance = self.get_object()

        if instance.status != Order.COMPLETED:
            detail = _('Only completed order can be reviewed.')
            raise exceptions.ValidationError(detail=detail)

        data = request.data
        data.update({'order': instance.pk})
        context = self.get_serializer_context()
        serializer = ReviewSerializer(data=data, context=context)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        instance.status = Order.REVIEWED
        instance.save()

        serializer = self.get_serializer(instance)
        return Response(serializer.data)
Example #12
0
class RatingTopicSerializer(serializers.ModelSerializer):
    # Defining the serializer for the foreign key
    review = ReviewSerializer()
    topic = TopicSerializer()

    class Meta:
        # Defining the serializer for the foreign key
        model = review_topic
        # Defining the serializer for the foreign key
        fields = ('id', 'review', 'topic', 'created')
Example #13
0
class RestaurantSerializer(serializers.ModelSerializer):

    foods = FoodSerializer(many=True, read_only=True)
    followers = StoreFollowerSerializer(many=True, read_only=True)
    address = AddressSerializer(read_only=True)
    reviews = ReviewSerializer(many=True, read_only=True)

    class Meta:
        model = Restaurant
        fields = ("id", "name", "content", "restaurant_banner_image", "restaurant_logo", "owner",'address','foods','followers','reviews')
Example #14
0
class CommentSerializer(serializers.ModelSerializer):
    # Defining the serializer for the foreign key
    user = UserSerializer()
    # Defining the serializer for the foreign key
    review = ReviewSerializer()

    class Meta:
        # Defining the model for the serializer class
        model = comment
        # Defining the fields for the serializer class
        fields = ('id', 'user', 'review', 'caption', 'description', 'created')
Example #15
0
class RatingSerializer(serializers.ModelSerializer):
    # Defining the serializer for the foreign key
    user=UserSerializer()
    # Defining the serializer for the foreign key
    review=ReviewSerializer()

    class Meta:
        # Defining the serializer for the foreign key
        model=rating
        # Defining the fields for the serializer class
        fields=('id', 'user', 'review', 'value')
    def test_retrieve_reviews(self):
        """test retrieving a list of reviews"""
        sample_review(reviewer=self.user)
        sample_review(reviewer=self.user)

        res = self.client.get(REVIEWS_URL)

        reviews = Review.objects.filter(reviewer=self.user).order_by('-id')
        serializer = ReviewSerializer(reviews, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
Example #17
0
    def post(self, request, *args, **kwargs):
        data = request.data
        booking_id = data.pop('booking_id')

        if Booking.objects.get(pk=booking_id).owner.id != request.user.id:
            return Response({}, status=status.HTTP_401_UNAUTHORIZED)

        serializer = ReviewSerializer(data=data)
        if serializer.is_valid():
            serializer.save()

            review = serializer.data.get('id')

            # Save review to booking
            booking = Booking.objects.get(pk=booking_id)
            booking.review_id = review
            booking.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors},
                        status=status.HTTP_200_OK)
Example #18
0
    def retrieve(self, request, *args, **kwargs):
        try:
            if Booking.objects.get(
                    pk=kwargs.get('pk')).owner.id != request.user.id:
                return Response({})
        except Booking.DoesNotExist:
            return Response({})

        queryset = self.get_object()

        serializer = ReviewSerializer(queryset, many=False)
        return Response(serializer.data)
Example #19
0
 def test_review_create_new_company_if_the_id_company_doesnt_exist(self):
     data = self._default_review_data()
     serializer = ReviewSerializer(data=data)
     serializer.is_valid()
     serializer.save(ip_address=self.faker.ipv4(),
                     reviewer=self._user_recipe.make())
     self.assertEquals(Company.objects.count(), 1)
    def test_retrieve_review_list(self):
        """Test retrieving a list of reviews"""

        create_dummy_review(self.user)
        create_dummy_review(self.user, 'Review 2')

        res = self.client.get(REVIEW_URL)

        Reviews = Review.objects.all().order_by('-title')
        serializer = ReviewSerializer(Reviews, many=True)

        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
    def create(self, request):
        '''
        Create a new review using the user authenticated by token
        '''
        request_data = request.data
        request_data['reviewer'] = {
            'user': {
                'username': request.user.username,
                'email': request.user.email
            },
            'key': '-'
        }
        # GET request IP
        request_data['ip_address'] = request.META.get(
            'HTTP_X_FORWARDED_FOR',
            request.META.get('REMOTE_ADDR')).split(',')[0]

        serializer = ReviewSerializer(data=request_data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=500)
        serializer.save()
        return Response(serializer.data, status=201)
Example #22
0
def reviewCreate_view(request):
    customer = Customer.objects.get(id = request.user.id)
    if request.method == 'POST':
        serializer = ReviewSerializer(data = request.data)
        if serializer.is_valid():
            serializer.save(customer=customer)
            serializer.save()
            logger.debug(f'Review object created, ID: {serializer.instance}')
            return Response(serializer.data, status=201)
        logger.warning(f'Review object was not created')
        logger.error(f'Server error')
        return Response(serializer.errors, status=500)
    def test_retrieve_reviews_limited_to_user(self):
        """test users cannot see reviews submitted by other users """
        user2 = get_user_model().objects.create_user('*****@*****.**',
                                                     'testpass')
        sample_review(reviewer=user2)
        sample_review(reviewer=self.user)

        res = self.client.get(REVIEWS_URL)

        reviews = Review.objects.filter(reviewer=self.user).order_by('-id')
        serializer = ReviewSerializer(reviews, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
        self.assertEqual(len(res.data), 1)
Example #24
0
def save_review(request):
    if request.method == "POST":
        try:
            data = JSONParser().parse(request)
            serializer = ReviewSerializer(data=data)

            user_no = data['user_no']
            food_no = Food.objects.get(food_name=data['food_name']).food_no
            serializer.initial_data['food_no'] = food_no

            # 먹은 음식의 후기 작성 여부 변경
            eaten_food = MapUserEat.objects.filter(user_no=user_no).get(
                food_no=food_no)
            if eaten_food.is_written == 1:
                return JsonResponse({"message": "ALREADY_WRITTEN"}, status=401)

            eaten_food.is_written = 1
            eaten_food.save()

            # 유효성 검사
            if not serializer.is_valid():
                print(serializer.errors)
                return JsonResponse({"message": "INVALID_FORM"}, status=402)

            # 리뷰 저장
            serializer.save()

            # 최근에 저장된 리뷰를 가져옴
            review = Review.objects.order_by('rev_no').last()

            # 음식 정보 업데이트 (평균 별점, 후기 수)
            food = Food.objects.get(food_no=food_no)
            star = food.food_star
            spicy = food.food_spicy
            cnt = food.food_review_count

            food.food_spicy = round(
                ((spicy * cnt) + serializer.validated_data['rev_spicy']) /
                (cnt + 1), 1)
            food.food_star = round(
                ((star * cnt) + serializer.validated_data['rev_star']) /
                (cnt + 1), 1)
            food.food_review_count = cnt + 1
            food.save()

            # 음식 태그 추가
            tags = data['tag_no']
            for i in range(len(tags)):
                MapFoodTag(rev_no=Review.objects.get(rev_no=review.rev_no),
                           food_no=Food.objects.get(food_no=food_no),
                           tag_no=Tag.objects.get(tag_no=tags[i])).save()

            return JsonResponse({"message": "SAVE_SUCCESS"}, status=200)

        except KeyError:
            return JsonResponse({"message": "INVALID_KEY"}, status=400)
Example #25
0
class BookingSerializer(serializers.ModelSerializer):
    detail = BookingDetailSerializer(many=True, read_only=True)
    review = ReviewSerializer(read_only=True)
    room = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(),
                                              write_only=True,
                                              many=True)
    night = serializers.IntegerField(source='nights', read_only=True)
    status = serializers.CharField(source='get_status_display', read_only=True)
    status_id = serializers.IntegerField(source='status',
                                         write_only=True,
                                         required=False)

    def to_representation(self, instance):
        representation = super(BookingSerializer,
                               self).to_representation(instance)
        representation['start_date'] = instance.start_date.strftime("%d %B %Y")
        representation['end_date'] = instance.end_date.strftime("%d %B %Y")
        return representation

    def create(self, validated_data):
        rooms = validated_data.pop('room')

        booking = Booking.objects.create(**validated_data)

        for r in rooms:
            night = (booking.end_date - booking.start_date).days
            detail = BookingDetail.objects.create(room=r,
                                                  booking=booking,
                                                  total_price=r.price * night)
            booking.detail.add(detail)

        return booking

    def validate(self, data):
        if 'start_date' in data.keys() and 'end_date' in data.keys():
            if data['start_date'] >= data['end_date']:
                raise serializers.ValidationError(
                    "Check-in Date must be after Check-out Date")
        return data

    class Meta:
        model = Booking
        fields = '__all__'
Example #26
0
class RestDetailSerializer(serializers.ModelSerializer):
    """ restaurant detail show review Serializer """
    # rest_count = serializers.ReadOnlyField()
    owner_rest = ReviewSerializer(many=True, read_only=True)

    class Meta:
        model = Restaurant
        fields = (
            'id',
            'rest_name',
            'rest_star',
            'rest_address',
            'rest_phone_number',
            'rest_food',
            'rest_sale',
            'rest_time',
            'rest_break_time',
            'owner_rest',
        )
        read_only_fields = ('rest_count', )
Example #27
0
 def get_ReviewData(self, obj):
     return ReviewSerializer(obj.ProductReviewID).data
Example #28
0
 def get_reviewDetails(self, obj):
     return ReviewSerializer(obj.review).data
Example #29
0
 def get_rating_count(self, obj):
     reviews = ReviewSerializer(obj.items_owner, many=True).data
     return len(reviews) if len(reviews) > 0 else 0
Example #30
0
class BasicProfileSerializer(serializers.ModelSerializer):
    social_links = SocialLinkSerializer(source='sociallink', many=False)
    descriptions = DescriptionSerializer(source='description_set', many=True)
    feedbacks = FeedbackSerializer(source='feedback_set', many=True)
    full_name = serializers.CharField(max_length=255, required=True, allow_blank=True)
    college = serializers.ReadOnlyField(source='college.name')
    year = serializers.ReadOnlyField(source='year.name')
    picture = serializers.SerializerMethodField('get_avatar_thumbnail')
    reviews = ReviewSerializer(source='items_owner', many=True)
    rating = serializers.SerializerMethodField()
    rating_count = serializers.SerializerMethodField()
    last_seen = serializers.SerializerMethodField()
    created_at = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('email', 'full_name', 'first_name', 'last_name', 'gender', 'age', 'college', 'year', 'picture',
                  'feedbacks', 'grand_total', 'reasons', 'about_me', 'payment_venmo', 'payment_paypal', 'username',
                  'created_at', 'last_seen', 'social_links', 'descriptions', 'id', 'is_online', 'connections',
                  'reviews', 'rating', 'rating_count', 'notification_email')

    def __init__(self, *args, depth=2, with_connections=True, **kwargs):
        if depth > 0 and with_connections:
            depth -= 1
            self.fields['connections'] = BasicProfileSerializer(depth=depth, with_connections=with_connections,
                                                                many=True, read_only=True)

        super(BasicProfileSerializer, self).__init__(*args, **kwargs)

    def get_avatar_thumbnail(self, obj):
        if obj.picture:
            url = get_thumbnail(obj.picture.path, '100x100', crop='center').url
            if settings.SITE_URL not in url:
                url = settings.SITE_URL + url
            return url
        else:
            return None

    def get_last_seen(self, obj):
        mins = (timezone.now() - obj.last_seen).total_seconds() // 60
        if mins >= 1440:
            mins = int(mins) // 1440
            unit = ' days ago'
        elif mins >= 60:
            mins = int(mins) // 60
            unit = ' hours ago'
        else:
            mins = int(mins)
            unit = ' minutes ago'
        return str(mins) + unit

    def get_created_at(self, obj):
        return obj.created_at.strftime('%b %dth, %Y')

    def update(self, instance, validated_data):
        instance.age = validated_data.get('age')
        full_name = validated_data.get('full_name').split(' ')
        instance.first_name = full_name[0]
        try:
            instance.last_name = full_name[1]
        except:
            instance.last_name = ''
        # instance.email = validated_data.get('email', instance.email)
        instance.save()

        return instance

    def to_internal_value(self, data):
        picture = data.pop('picture')[0]
        if not isinstance(picture, str) or not isinstance(picture, six.text_type):
            self.instance.picture = picture

        sociallinks = json.loads(data.pop('social_links', None)[0])
        if sociallinks:
            if not hasattr(self.instance, 'sociallink'):
                self.instance.sociallink = SocialLink()
            self.instance.sociallink.twitter = sociallinks['twitter']
            self.instance.sociallink.instagram = sociallinks['instagram']
            self.instance.sociallink.facebook = sociallinks['facebook']
            self.instance.sociallink.googleplus = sociallinks['googleplus']
            self.instance.sociallink.save()

        self.instance.description_set.all().delete()
        descriptions = json.loads(data.pop('descriptions', None)[0])
        for desc in descriptions:
            desc_obj = Description(description=desc['description'], user=self.instance)
            desc_obj.save()

        ret = super(BasicProfileSerializer, self).to_internal_value(data)
        return ret

    def get_rating(self, obj):
        average = 0.0
        reviews = ReviewSerializer(obj.items_owner, many=True).data
        if len(reviews) > 0:
            for item in reviews:
                average += item['rating']
            average /= len(reviews)
        return average

    def get_rating_count(self, obj):
        reviews = ReviewSerializer(obj.items_owner, many=True).data
        return len(reviews) if len(reviews) > 0 else 0
Example #31
0
 def get_AllReviews(self, obj):
     return ReviewSerializer(obj.review).data