def post(self, request, place_id, format=None):
        """
        Creates a Review
        """

        try:
            place = Place.objects.get(id=place_id)
        except ObjectDoesNotExist:
            raise NotFound(detail="Place not found")

        data = JSONParser().parse(request)

        if 'user_id' not in data:
            raise ParseError(detail="Missing user_id", code=400)

        try:
            user = User.objects.get(id=data['user_id'])
        except ObjectDoesNotExist:
            raise NotFound(detail="User not found")

        if 'text' not in data:
            raise ParseError(detail="Missing text", code=400)

        data["place"] = place.id
        data["user"] = user.id

        serializer = ReviewSerializer(data=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)
Beispiel #2
0
    def test_validate_beyond_five_rating(self):
        self.data['rating'] = 6
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('rating')), 1)
Beispiel #3
0
    def test_validate_invalid_ip_address(self):
        self.data['ip_address'] = '127,0,0,1'
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('ip_address')), 1)
    def test_to_internal_value_adds_ip_and_reviewer(
            self, mock_req):
        user = factories.UserFactory(username='******')
        mock_req.META = {
            'HTTP_X_FORWARDED_FOR': '192.0.0.1',
            'REMOTE_ADDR': '142.0.0.1'
        }
        mock_req.user = user
        mock_req.versionong_scheme.get_versioned_viewname.return_value = ''

        s = ReviewSerializer(context={'request': mock_req}, partial=True)

        data = {
            "rating": 5,
            "title": "test title",
            "summary": "test summary",
        }
        expected_ret = {
            "rating": 5,
            "title": "test title",
            "summary": "test summary",
            "ip_address": "192.0.0.1",
            "reviewer": user.reviewer

        }
        ret = s.to_internal_value(data)
        self.assertEqual(ret, expected_ret)
Beispiel #5
0
    def test_validate_long_summary(self):
        self.data['summary'] = ''.join(['a' for i in range(10001)])
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('summary')), 1)
    def test__get_request_user_no_reviewer(self, mock_req):
        user = factories.UserFactory(username='******', reviewer=None)
        mock_req.user = user

        s = ReviewSerializer(context={'request': mock_req})
        with self.assertRaises(ValidationError):
            s._get_request_user()
    def post(self, request):
        data = json.loads(request.body)
        serializer = ReviewSerializer(data=data)
        if not serializer.is_valid():
            return JsonResponse({'errors': serializer.errors},
                                status=status_codes.HTTP_400_BAD_REQUEST)
        clean_data = serializer.validated_data

        business = User.objects.filter(
            username=clean_data['business_username'],
            is_business=True).first()
        if not business:
            return JsonResponse({'errors': 'Business ID Provided is invalid'},
                                status=status_codes.HTTP_403_FORBIDDEN)

        user = User.objects.get(id=request.user.id)
        if not user:
            return JsonResponse(
                {'error': 'user not found'},
                status=status_codes.HTTP_500_INTERNAL_SERVER_ERROR)

        model = BusinessReviews(
            user_id=request.user.id,
            user_name=user.name,
            business_username=clean_data['business_username'],
            review_text=clean_data['review_text'],
            stars=clean_data['stars'])
        model.save()
        return JsonResponse({'data': model.to_dict()},
                            status=status_codes.HTTP_200_OK)
Beispiel #8
0
 def post(self, request, *args, **kwargs):
     data = request.data
     data['ip_address'] = request.META.get('REMOTE_ADDR')
     serializer = ReviewSerializer(data=data)
     if serializer.is_valid():
         serializer.save(user=request.user)
         return Response(serializer.data, status.HTTP_201_CREATED)
     return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
Beispiel #9
0
    def test_validate_long_title(self):
        self.data[
            'title'] = 'This is a very very very very very very very very very long title'
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertFalse(serializer.is_valid())
        self.assertEqual(len(serializer.errors.get('title')), 1)
Beispiel #10
0
 def post(self, request, pk):
     request.data['movie_id']=pk
     serializer = ReviewSerializer(data=request.data)
     if serializer.is_valid():
         # serializer.movie_id = pk
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
 def test__get_ip_address_from_request_no_match(self, mock_req):
     mock_req.META = {
         'HTTP_X_FORWARDED_FOR': '',
         'REMOTE_ADDR': ''
     }
     s = ReviewSerializer(context={'request': mock_req})
     expected_ret = ''
     ret = s._get_ip_address_from_request()
     self.assertEqual(ret, expected_ret)
    def test__get_request_user_known_user(self, mock_req):
        user = factories.UserFactory(username='******')
        reviewer = user.reviewer
        mock_req.user = user

        s = ReviewSerializer(context={'request': mock_req})
        expected_ret = reviewer
        ret = s._get_request_user()
        self.assertEqual(ret, expected_ret)
Beispiel #13
0
 def create(self, request):
     serializer = ReviewSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save(card_id=request.data['card'])
         card = Card.objects.get(pk=request.data['card'])
         card.review(request.data['answer_quality'])
         card.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def test__get_ip_address_from_request_client_forward(self, mock_req):
        mock_req.META = {
            'HTTP_X_FORWARDED_FOR': '192.0.0.1',
            'REMOTE_ADDR': '142.0.0.1'
        }

        s = ReviewSerializer(context={'request': mock_req})
        expected_ret = '192.0.0.1'
        ret = s._get_ip_address_from_request()
        self.assertEqual(ret, expected_ret)
Beispiel #15
0
 def post(self, request):
     request.data["reviewer"] = request.user.id
     ip = get_client_ip(request)[0]
     request.data["ip"] = self.convert_ip(ip)
     serializer = ReviewSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response({'error': serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Beispiel #16
0
    def critical(self, request):
        critical_reviews = get_users_critical_reviews(request.user)
        page = self.paginate_queryset(critical_reviews)

        if page is not None:
            serializer = ReviewSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = ReviewSerializer(critical_reviews, many=True)
        return Response(serializer.data)
Beispiel #17
0
 def put(self, request, review_id):
     review = self.get_object(review_id)
     request.data["reviewer"] = request.user.id
     ip = get_client_ip(request)[0]
     request.data["ip"] = self.convert_ip(ip)
     serializer = ReviewSerializer(instance=review, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response({'error': serializer.errors},
                     status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    def test__get_request_user_anon_user(self, mock_req):
        # set the property, then reset when done
        user = factories.UserFactory(username='******', reviewer=None)
        type(user).is_anonymous = mock.PropertyMock(return_value=True)
        mock_req.user = user

        s = ReviewSerializer(context={'request': mock_req})
        with self.assertRaises(ValidationError):
            s._get_request_user()

        type(user).is_anonymous = mock.PropertyMock(return_value=False)
Beispiel #19
0
 def get(self, request, **kwargs):
     if kwargs.get('review_id') is None:
         review_queryset = Review.objects.all()
         review_queryset_serializer = ReviewSerializer(review_queryset,
                                                       many=True)
         return Response(review_queryset_serializer.data,
                         status=status.HTTP_200_OK)
     else:
         review_id = kwargs.get('review_id')
         review_serializer = ReviewSerializer(
             Review.objects.get(review_id=review_id))
         return Response(review_serializer.data, status=status.HTTP_200_OK)
Beispiel #20
0
def createReview(request, pk):
    if request.user.is_anonymous == False:

        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            product = Product.objects.get(id=pk)
            serializer.save(user=request.user, product=product)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    else:
        return Response(status=status.HTTP_401_UNAUTHORIZED)
Beispiel #21
0
    def test_deserialize_data(self):
        serializer = ReviewSerializer(data=self.data)

        self.assertIsInstance(serializer, serializers.ModelSerializer)
        self.assertTrue(serializer.is_valid())

        validated_data = serializer.validated_data

        self.assertEqual(validated_data.get('title'), 'My review')
        self.assertEqual(validated_data.get('summary'),
                         'This is my first review.')
        self.assertEqual(validated_data.get('rating'), 1)
        self.assertEqual(validated_data.get('ip_address'), '127.0.0.1')
        self.assertEqual(validated_data.get('company'), 'Some Company')
        self.assertEqual(validated_data.get('reviewer'), 'Some Reviewer')
Beispiel #22
0
 def get(self, request):
     if request.user.is_staff == 1:
         reviews = Review.objects.all()
         serializer = ReviewSerializer(reviews, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)
     return Response({'details': 'permission denied'},
                     status=status.HTTP_403_FORBIDDEN)
Beispiel #23
0
 def get(self, request):
     if request.user.is_superuser:
         reviews = Review.objects.all()
     else:
         reviews = Review.objects.filter(reviewer=request.user)
     serializer = ReviewSerializer(reviews, many=True)
     return Response(serializer.data)
Beispiel #24
0
def book_detail(request, book_id):
    try:
        book = Book.objects.get(id=book_id)
    except Book.DoesNotExist as e:
        return Response({'error': str(e)})

    if request.method == 'GET':
        serializer = BookSerializer(book)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response({'error': serializer.errors},
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'PUT':
        serializer = BookSerializer(instance=book, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response({'error': serializer.errors})

    elif request.method == 'DELETE':
        book.delete()

        return Response({'deleted': True})
Beispiel #25
0
def get_user_reviews(request):
    if request.method == 'GET':
        if request.user.is_anonymous:
            return Response(status=status.HTTP_401_UNAUTHORIZED)
        else:
            reviews = Review.objects.for_user(request.user)
            serializer = ReviewSerializer(reviews, many=True)
            return Response(serializer.data)
Beispiel #26
0
 def get(self, request, **kwargs):
     user_id = request.GET.get('user_id', '00000000000')
     review_queryset = Review.objects.filter(
         user_id=user_id).order_by('date')
     review_queryset_serializer = ReviewSerializer(review_queryset,
                                                   many=True)
     return Response(review_queryset_serializer.data,
                     status=status.HTTP_200_OK)
Beispiel #27
0
 def get(self, request):
     try:
         reviews = Review.objects.all()
         serializer = ReviewSerializer(reviews, many=True)
         return Response(serializer.data, status=status.HTTP_200_OK)
     except:
         return Response({"error": "Error getting reviews"},
                         status=status.HTTP_404_NOT_FOUND)
Beispiel #28
0
def get_reviews(request, pk):
    try:
        product = Product.objects.get(id=pk)
        reviews = product.reviews.all()
        serializer = ReviewSerializer(reviews, many=True)
        return Response(serializer.data)
    except Product.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    def get(self, request, review_id, format=None):
        """ Retrieves a specific Review """
        try:
            review = Review.objects.get(id=review_id)
        except ObjectDoesNotExist:
            raise NotFound(detail="Review not found")

        return Response(ReviewSerializer(review).data)
Beispiel #30
0
 def update(self, request, pk):
     review = Review.objects.for_user(self.request.user).get(id=pk)
     review.text = request.data['text']
     review.save()
     serializer = ReviewSerializer(review)
     logger.debug(f'Review {serializer.instance} was updated')
     logger.info(f'Review {serializer.instance} was updated')
     return Response(serializer.data)