def test_company_rating_two_point_five(self): """The company rating should be two point five""" company = Company.objects.get(name="test_apple_test") reviewer = Reviewer.objects.get(name="john") client = Client.objects.get(username='******') review = Review.objects.create( rating=5, title="review", summary="review text", ip="127.0.0.1", company=company, reviewer=reviewer, client=client ) review = Review( rating=1, title="review", summary="review text", ip="127.0.0.1", company=company, reviewer=reviewer, client=client ) review.save() company.update_average_rating() self.assertEqual(company.get_rating(), 3)
def test_review_stats(self): stats = Review.stats() self.assertEqual(stats.total_reviews, 0) self.assertEqual(stats.avg_rating, 0) for r in range(MIN_RATING_VALUE, MAX_RATING_VALUE + 1): self.assertEqual(getattr(stats, 'total_{}_rates'.format(r)), 0) self.assertEqual(getattr(stats, 'avg_{}_rates'.format(r)), 0) for r in range(MIN_RATING_VALUE, MAX_RATING_VALUE + 1): user = User.objects.create_user('testuser{}'.format(r), 'user{}@test.com'.format(r), 'insertstrongpassword') Review.objects.create(user=user, rating=r, comment='Comment {}'.format(r)) stats = Review.stats() self.assertEqual(stats.total_reviews, MAX_RATING_VALUE) self.assertEqual( stats.avg_rating, sum([i for i in range(MIN_RATING_VALUE, MAX_RATING_VALUE + 1)]) / MAX_RATING_VALUE) for r in range(MIN_RATING_VALUE, MAX_RATING_VALUE + 1): self.assertEqual(getattr(stats, 'total_{}_rates'.format(r)), 1) self.assertEqual(getattr(stats, 'avg_{}_rates'.format(r)), r)
def test_can_create_a_review(self): user = get_user_model().objects.create(username='******') category = Category.objects.create( title='category', slug='catslug', featured=False, image='test.png', ) product = Product.objects.create( name='testproduct', slug="testslug", category=category, image='image.png', summary="summary", description="description", price=19.99, ) review = Review( user=user, product=product, title='test', review='review', rating=4.0, ) review.save() self.assertEqual(review.user, user) self.assertEqual(review.product, product) self.assertEqual(review.title, 'test') self.assertEqual(review.review, 'review') self.assertEqual(review.rating, 4.0)
def extract_review_from_row(review_row): review = Review(id=review_row["id"], author=review_row["username"], item=Item.objects.get(id=review_row["item_id"]), rating=review_row["rating"], review=review_row["comment"], pub_date=datetime.datetime.now()) review.save()
def extract_review_from_row(review_row): review = Review(id = review_row["id"], author = review_row["username"], item = Item.objects.get(id=review_row["item_id"]), rating = review_row["rating"], review = review_row["comment"], pub_date = datetime.datetime.now() ) review.save()
def save_review_from_row(review_row): review = Review() review.id = review_row[0] review.user_name = review_row[1] review.repo = Repo.objects.get(id=review_row[2]) review.rating = review_row[3] review.pub_date = datetime.datetime.now() review.comment = review_row[4] review.save()
def product_review(request, pk): if request.method == 'POST': if request.user.is_authenticated: r = Review(user=request.user, text=request.POST.get('description'), product=Product.objects.get(id=pk), rating=int(request.POST.get('mark'))) r.save() return redirect('product_page', pk=pk)
def test_rating_min_validator1(self): rev = Review(date=self.date, review_content='test test1', sender_email='*****@*****.**', sender_user_name='test123', rating=1, id=0) rev.save() self.assertEqual(Review.objects.filter(rating=1).count(), 1)
def add_review(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data["rating"] print(rating) print(form.cleaned_data) comment = form.cleaned_data["comments"] user_name = request.user.username review = Review() review.wine = wine review.user_name = user_name review.rating = rating review.comments = comment review.pub_date = datetime.datetime.now() review.save() update_clusters() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect( reverse("reviews:wine_detail", args=(wine.id, ))) return render(request, "reviews/wine_detail.html", { "wine": wine, "form": form })
def test_review_class_rating_choices_returned_value(): new_review = Review() RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) new_review.return_rating_choices = MagicMock(return_value=RATING_CHOICES) assert new_review.return_rating_choices() == RATING_CHOICES
def save_review_from_row(review_row): review = Review() review.id = review_row[0] review.user_name = review_row[1] review.wine = Wine.objects.get(id=review_row[2]) review.rating = review_row[3] review.pub_date = datetime.datetime.now() review.comment = review_row[4] review.save()
def create_reviews(user, business): reviews = [] review = Review.create(user.id, business, 1, 'This is not good.', tags=['hello', 'world']) reviews.append(review) review = Review.create(user.id, business, 1, 'This is also not good.', tags=['hello', 'example']) reviews.append(review) review = Review.create(user.id, business, 5, 'This is awesome.', tags=['awesome']) reviews.append(review) return reviews
def create_review(self, commit=True): review = Review(product=self.product) review.rating = self.data['rating'] review.summary = self.data['summary'] review.review = self.data['review'] review.user = self.request.user if commit: review.full_clean() review.save() return review
def save_review_from_row(review_row): review = Review() review.id = review_row[0] review.user_name = review_row[1] # This can be an error if you gave not imported the wines yet review.wine = Wine.objects.get(id=review_row[2]) review.rating = review_row[3] review.pub_date = datetime.datetime.now() review.comment = review_row[4] review.save()
def get_rotten_tomates(): for movie in Movie.objects.all(): if len(RT('bt7f4pcbku6m9mqzuhhncc9e').search(movie.name))==0: break movie_id=RT('bt7f4pcbku6m9mqzuhhncc9e').search(movie.name)[0]['id'] for j in range(len(RT('bt7f4pcbku6m9mqzuhhncc9e').info(movie_id, 'reviews')['reviews'])): reviewblob = RT('bt7f4pcbku6m9mqzuhhncc9e').info(movie_id, 'reviews')['reviews'] quote=reviewblob[j]['quote'] fresh_bool='fresh' in reviewblob[j]['freshness'] name= reviewblob[j]['critic'] print(quote) print(name) review= Review(name=name, body=quote, fresh=fresh_bool, movie=movie) review.save()
def test_rating_min_validator(self): rev = Review(date=self.date, review_content='test test1', sender_email='*****@*****.**', sender_user_name='test123', rating=0, id=0) try: rev.full_clean() except ValidationError as err: self.assertEqual( str(err), "{'rating': ['Ensure this value is greater than or equal to 1.']}" )
def post(self, request, pk): url = f'/furniture/details/{self.get_object().id}/' post_values = request.POST.copy() form = ReviewForm(post_values) if form.is_valid(): author = Profile.objects.get(user__pk=request.user.id) post_values['furniture'] = self.get_object() review = Review(content=post_values['content'], score=post_values['score'], furniture=self.get_object(), author=author) review.save() return HttpResponseRedirect(url)
def test_review_replies(self): """ Make sure that developer replies are not returned as if they were original reviews. """ addon = Addon.objects.get(id=3615) u = UserProfile.objects.get(pk=2519) version = addon.get_version() new_review = Review(version=version, user=u, rating=2, body='hello', addon=addon) new_review.save() new_reply = Review(version=version, user=u, reply_to=new_review, addon=addon, body='my reply') new_reply.save() review_list = [r.pk for r in u.reviews] eq_(len(review_list), 1) assert new_review.pk in review_list, ( 'Original review must show up in review list.') assert new_reply.pk not in review_list, ( 'Developer reply must not show up in review list.')
def save_review_from_row(review_row): review = Review() review.user_name = review_row[0] review.comment = review_row[1] review.rating = review_row[2] review.movie_id = review_row[3] review.save()
def save_review_from_row(review_row): review=Review() review.id=review_row[0] review.user_name=review_row[1] # we use the wine id to look for the wine instance # this means that we need to load wines before we load reviews review.wine=Wine.objects.get(id=review_row[2]) review.rating=review_row[3] review.pub_date=datetime.datetime.now() review.comment=review_row[4] review.save()
def save_review_from_row(review_row): review = Review() # review.id = review_row[0] review.user_name = review_row[0] # review.wine = Wine.objects.get(id=review_row[2]) # print(review.wine) review.wine = review_row[1] review.rating = review_row[3] review.pub_date = datetime.datetime.now() review.comment = review_row[2] review.save()
def test_ensure_ratings_are_valid(self): upper = Review(rating=6) upper.save() self.assertEqual((upper.rating<=5),True) lower = Review(rating=0) lower.save() self.assertEqual((lower.rating>0),True)
def save_review_from_row(sword_row): if sword_row.note != 'missing': review = Review() review.comment = sword_row.note review.author_id = randint(1, 4) review.sword_id = sword_row.name review.rating = randint(1, 5) review.save()
def setup(self): self.new_wine = Wine(name='Wine1') self.new_review = Review(wine=self.new_wine, pub_date=datetime(2015, 1, 1, 12, 30, 59, 0), user_name='admin', comment='Best wine', rating=4)
def reset(self): for _id in self.created_ids: review = Review.get_by_id(_id) review.delete() self.user.delete() self.business.delete()
def review_list(request, addon, review_id=None, user_id=None, rating=None): qs = Review.objects.valid().filter(addon=addon).order_by('-created') ctx = {'product': addon, 'score': rating, 'review_perms': {}} if review_id is not None: qs = qs.filter(pk=review_id) ctx['page'] = 'detail' # If this is a dev reply, find the first msg for context. review = get_object_or_404(Review, pk=review_id) if review.reply_to_id: review_id = review.reply_to_id ctx['reply'] = review elif user_id is not None: qs = qs.filter(user=user_id) ctx['page'] = 'user' if not qs: raise http.Http404() else: ctx['page'] = 'list' qs = qs.filter(is_latest=True) ctx['ratings'] = ratings = amo.utils.paginate(request, qs, 20) if not ctx.get('reply'): ctx['replies'] = Review.get_replies(ratings.object_list) if request.user.is_authenticated(): ctx['review_perms'] = { 'is_admin': acl.action_allowed(request, 'Addons', 'Edit'), 'is_editor': acl.check_reviewer(request), 'is_author': acl.check_addon_ownership(request, addon, viewer=True, dev=True, support=True), } ctx['flags'] = get_flags(request, ratings.object_list) ctx['has_review'] = addon.reviews.filter(user=request.user.id).exists() return jingo.render(request, 'ratings/listing.html', ctx)
def init_comment(self, username, reviewername, gamename): comment_user = User(username=username) comment_user.save() review_user = User(username=reviewername) review_user.save() game = Game(name=gamename, releaseDate=date.today()) game.save() review = Review(poster=review_user, game=game, post_datetime=date.today()) review.save() return Comment(poster=comment_user, review=review, comment_text='test', post_datetime=date.today(), votes=1)
def update_business(event): """ compiles rating and tags for a business when a review is updated """ from reviews.models import Review review = event.review business = Business.get_by_id(review.reviewed_id) if business: business.rating = Review.rating_for_reviewed(review.reviewed_id) business.tags = Review.tags_for_reviewed(review.reviewed_id) business.save() logger.debug('updated business:{} reviews'.format(business.id)) else: logger.debug('failed to update business:{} reviews'.format(review.reviewd_id))
def create_review(request): if request.method == 'POST': print "Received POST" try: rating = request.POST['rating'] course = request.POST['course'] author = request.POST['author'] professor = request.POST['professor'] rating = int(request.POST['rating']) text = request.POST['text'] if rating >= 1 and rating <= 5: courseobj = None try: courseobj = Course.objects.get(coursename=course) except Course.DoesNotExist: courseobj = Course(coursename=course) courseobj.save() r = Review(course=courseobj, author=author, professor=professor, score=rating, text=text) r.save() print "Saved %s" % r return HttpResponseRedirect( reverse('course_reviews', args=(course, ))) else: raise ValueError() except: context = { 'error_message': "Please fill all fields", 'course': course, 'author': author, 'professor': professor, 'rating': rating, 'text': text } return render(request, 'reviews/create_review.html', context) else: return render(request, 'reviews/create_review.html', None)
def get_dummy_reviews(revision): """Return a dictionary of Review objects for.""" cache_key = 'dummy_reviews_{}'.format(revision.metadata.document_id) dummy_reviews = cache.get(cache_key, None) if dummy_reviews is None: revisions = revision.__class__.objects \ .filter(metadata__document=revision.document) \ .filter(review_start_date=None) \ .select_related('leader', 'approver') \ .prefetch_related('reviewers') dummy_reviews = {} for revision in revisions: revision_reviews = [] for reviewer in revision.reviewers.all(): revision_reviews.append( Review(role='reviewer', status=Review.STATUSES.void, reviewer=reviewer, document_id=revision.metadata.document_id)) if revision.leader: revision_reviews.append( Review(role='leader', status=Review.STATUSES.void, reviewer=revision.leader, document_id=revision.metadata.document_id)) if revision.approver: revision_reviews.append( Review(role='approver', status=Review.STATUSES.void, reviewer=revision.approver, document_id=revision.metadata.document_id)) dummy_reviews[revision.revision] = revision_reviews cache.set(cache_key, dummy_reviews, 5) return dummy_reviews
def new(request): if not request.user.is_authenticated(): return HttpResponseForbidden user = request.user data = json.loads(request.body.decode('utf-8')) restaurant = get_object_or_404(Restaurant, id=data['restaurantId']) review = Review(title=data['title'], body=data['body'], user=user, restaurant=restaurant) try: review.save() except: return HttpResponseBadRequest return HttpResponse('OK')
def init_review(self, username, gamename): user = User(username=username) user.save() game = Game(name=gamename, releaseDate=date.today()) game.save() return Review(poster=user, game=game, review_text='test', rating=1, post_datetime=date.today(), votes=1)
def test_reviews(self): review = Review.create(self.user.id, self.business, 1, 'This is a review', tags=['hello', 'world']) self.created_ids.append(review.id) review = Review.create(self.user.id, self.business, 5, 'This is a another review', tags=['hello', 'something']) self.created_ids.append(review.id) self.business = Business.get_by_id(self.business.id) self.assertTrue(self.business.rating == 3) self.assertTrue('hello' in self.business.tags) self.assertTrue('world' in self.business.tags) self.assertTrue('something' in self.business.tags) review.delete() self.business = Business.get_by_id(self.business.id) self.assertTrue(self.business.rating == 1) self.assertFalse('something' in self.business.tags) review = Review.create(self.user.id, self.business, 5, 'This is a another review', tags=['hello', 'something']) self.created_ids.append(review.id)
def reviews_post(request): """ creates new business review **authentication required with access_token** errors ====== * status 400 - if failed to create business returns ======= :: { "id": "" } """ business_id = request.matchdict['business_id'] business = Business.get_by_id(business_id) user = request.validated['user'] text = request.validated['text'] rating = request.validated['rating'] tags = request.validated['tags'] if tags: tags = tags.split(':') else: tags = [] if business and user: review = Review.create(user.id, business, rating, text, tags) response_body = { 'id': review.id, } # kill cache cache_key = 'business:{}*'.format(business.id) redis_cache.delete_pattern(cache_key) else: logger.debug('Failed to create review for business:{}'.format(business_id)) request.response.status_int = 400 response_body = { 'status': 'error', 'message': 'failed to create review for business' } request.response.body = json.dumps(response_body, cls=ComplexEncoder) request.response.content_type = 'application/json' return request.response
def add_review(request): if request.method == 'POST': form = AddReview(request.POST) if form.is_valid(): name = request.POST.get('reviewer', '') place_name = request.POST.get('place_name', '') image = request.POST.get('image', '') review = request.POST.get('review', '') r = Review(reviewer=name, place_name=place_name, image=image, review=review) r.save() return HttpResponseRedirect('add_new_data') else: form = AddReview() return render(request, 'add_review.html', { 'form': form, })
def get_rotten_tomates(): for movie in Movie.objects.all(): if len(RT('bt7f4pcbku6m9mqzuhhncc9e').search(movie.name)) == 0: break movie_id = RT('bt7f4pcbku6m9mqzuhhncc9e').search(movie.name)[0]['id'] for j in range( len( RT('bt7f4pcbku6m9mqzuhhncc9e').info( movie_id, 'reviews')['reviews'])): reviewblob = RT('bt7f4pcbku6m9mqzuhhncc9e').info( movie_id, 'reviews')['reviews'] quote = reviewblob[j]['quote'] fresh_bool = 'fresh' in reviewblob[j]['freshness'] name = reviewblob[j]['critic'] print(quote) print(name) review = Review(name=name, body=quote, fresh=fresh_bool, movie=movie) review.save()
def reset(self): """ clean up any remaining test users """ for _id in self.created_ids: review = Review.get_by_id(_id) if review: review.delete() self.user.delete() self.business.delete()
def reviews_get(request): """ Returns the business reviews errors ====== * status 404 - if the business can't be found returns ======= :: { "reviews": [ { "rating": 5, "modified": "2015-08-10T00:20:17.753000", "id": "55c7ee41fad9b43993d71919", "user_id": "55c7ee3dfad9b43993d7190e", "reviewed_id": "55c7ee3efad9b43993d7190f", "tags": [ "awesome" ], "text": "This is awesome.", "created": "2015-08-10T00:20:17.753000", "reviewed_collection": "businesses" } ] } """ business_id = request.matchdict['business_id'] business = Business.get_by_id(business_id) if business: response_body = { 'reviews': Review.reviews_for_reviewed(business.collection, business.id) } logger.debug('Retrieved business:{} reviews'.format(business.id)) else: logger.debug('Failed to retrieve business:{} reviews'.format(business_id)) request.response.status_int = 404 response_body = { 'status': 'error', 'message': 'failed to find business' } request.response.body = json.dumps(response_body, cls=ComplexEncoder) request.response.content_type = 'application/json' return request.response
def write_review_view(request, product_slug): product = Product.objects.filter(slug=product_slug).first() review_form = ReviewForm(request.POST or None) if request.method == 'POST': if review_form.is_valid(): title = review_form.cleaned_data['title'] body = review_form.cleaned_data['body'] score = review_form.cleaned_data['score'] new_review = Review(user = request.user , product = product , title=title, body=body, score=score) new_review.save() return redirect('product_view', product_slug=product_slug) context = { 'product': product, 'review_form': review_form, } return render(request, 'products/write_review.html', context)
def save_reviews(csvpath): df = pd.read_csv(csvpath) data = df.to_dict(orient='records') updated_data = [] for item in data: updated_item = {**item, 'game': Game.objects.get(id=item['game_id'])} updated_item.pop('game_id') updated_data.append(Review(**updated_item)) Review.objects.bulk_create(updated_data) return len(updated_data)
def new(request): review = Review() if request.method == 'POST': title = request.POST['title'] description = request.POST['description'] author = request.user name = slugify(title) unique_name = name i = 0 while Review.objects.filter(name=unique_name, author__username=request.user.username): i = i + 1 unique_name = name + '-' + str(i) review = Review(name = unique_name, title = title, description = description, author=author) is_valid = True if not title: is_valid = False messages.add_message(request, messages.ERROR, 'Title is a required field.') elif len(title) > 250: is_valid = False messages.add_message(request, messages.ERROR, 'The title should not exceed 250 characters.') if len(description) > 500: is_valid = False messages.add_message(request, messages.ERROR, 'The description should not exceed 500 characters.') if is_valid: review.save() messages.add_message(request, messages.SUCCESS, 'Review created with success.') return redirect('/' + review.author.username + '/' + review.name + '/') context = RequestContext(request, {'review': review}) return render_to_response('reviews/new.html', context)
def save_review_from_row(review_row): review = Review() # id, username, wine_id, rating, published_date, comment review.id = int(review_row[0]) + 1 review.user_name = review_row[5] review.wine = Wine.objects.get(id=review_row[2]) review.rating = review_row[3] review.pub_date = datetime.datetime.now() review.comment = datetime.datetime.fromtimestamp(int( review_row[4])).strftime('%Y-%m-%d %H:%M:%S') print(review.id, review.user_name, review.wine, review.rating, review.pub_date, review.comment) review.save()
def test_create_review(self): service = Service(name="Test Service for review", description="Test description service review", price=29) review = Review(service=service, date=timezone.now(), comments="test review", rating=4) self.assertEqual(review.service.name, "Test Service for review") self.assertEqual(review.comments, "test review") self.assertEqual(review.rating, 4) self.assertFalse(review.approved)
def test_create_review(self): Review.author = User(username='******') review = Review(game_title='Breath Of The Wild', author='Teddy', platform='Switch', review='Absolutely breath-taking game!', score='9') self.assertEqual(review.game_title, 'Breath Of The Wild') self.assertEqual(review.author, 'Teddy') self.assertEqual(review.platform, 'Switch') self.assertEqual(review.review, 'Absolutely breath-taking game!') self.assertEqual(review.score, '9')
def review_parsing(self, review_results, restaurant, user_list): for i in range(5): try: review_dict = review_results[i] except IndexError: break owner = random.choice(user_list) order = Order.objects.create( restaurant=restaurant, owner=owner, address='as', payment_method=Order.PaymentMethodChoice.CASH, total_price=1000, status=Order.OrderStatusChoice.DELIVERY_COMPLETE) review = Review( owner=owner, restaurant=restaurant, order=order, menu_name=review_dict['menu_summary'][:100], rating=review_dict['rating'], taste=review_dict['rating_taste'], delivery=review_dict['rating_delivery'], amount=review_dict['rating_quantity'], caption=review_dict['comment'][:298], like_count=review_dict['like_count'], ) review.save() for img in review_dict['review_images']: review_image = ReviewImage(review=review) review_image.image.save(*self.save_img(img['thumb'])) owner_reply = review_dict['owner_reply'] if owner_reply: review_comment = OwnerComment( review=review, comments=owner_reply['comment'], ) review_comment.save()
def create_review(request): if request.method == 'POST': print "Received POST" try: rating = request.POST['rating'] course = request.POST['course'] author = request.POST['author'] professor = request.POST['professor'] rating = int(request.POST['rating']) text = request.POST['text'] if rating >= 1 and rating <= 5: courseobj = None try: courseobj = Course.objects.get(coursename=course) except Course.DoesNotExist: courseobj = Course(coursename=course) courseobj.save() r = Review(course=courseobj, author=author, professor=professor, score=rating, text=text) r.save() print "Saved %s" % r return HttpResponseRedirect(reverse('course_reviews', args=(course,))) else: raise ValueError() except: context = { 'error_message': "Please fill all fields", 'course': course, 'author': author, 'professor': professor, 'rating': rating, 'text': text } return render(request, 'reviews/create_review.html', context) else: return render(request, 'reviews/create_review.html', None)
def review_get(request): """ Returns the business review errors ====== * status 404 - if the review couldn't be found returns ======= :: { "rating": 5, "modified": "2015-08-10T00:20:17.753000", "id": "55c7ee41fad9b43993d71919", "user_id": "55c7ee3dfad9b43993d7190e", "reviewed_id": "55c7ee3efad9b43993d7190f", "tags": [ "awesome" ], "text": "This is awesome.", "created": "2015-08-10T00:20:17.753000", "reviewed_collection": "businesses" } """ business_id = request.matchdict['business_id'] review_id = request.matchdict['review_id'] business = Business.get_by_id(business_id) review = Review.get_by_id(review_id) if business and review and business.id == review.reviewed_id: response_body = review.json logger.debug('Retrieved business:{} review:{}'.format(business.id, review.id)) else: logger.debug('Failed to retrieve business:{} review:'.format(business_id, review_id)) request.response.status_int = 404 response_body = json.dumps({ 'status': 'error', 'message': 'failed to find business review' }) request.response.body = response_body request.response.content_type = 'application/json' return request.response
def new_review(request, slug, format=None): """Create new review for tutor.""" profile = get_object_or_404(Profile, slug=slug) if request.method == 'POST': content = request.POST.get('content') # If current user is tutee and profile user is tutor and content if request.user.profile.tutee and profile.tutor and content: if request.POST.get('positive'): if int(request.POST.get('positive')): positive = True else: positive = False review = Review() review.content = content review.positive = positive review.tutee = request.user review.tutor = profile.user review.save() if format: if format == '.js': d = { 'review': review, 'static': settings.STATIC_URL, 'userd': profile.user, } new_review_form = loader.get_template( 'reviews/new_review_form.html') review_template = loader.get_template( 'reviews/review.html') context = RequestContext(request, add_csrf(request, d)) data = { 'new_review_form': new_review_form.render(context), 'review_template': review_template.render(context), } elif format == '.json': data = { 'review': review.to_json(), } return HttpResponse(json.dumps(data), mimetype='application/json') else: messages.success(request, 'Review submitted') return HttpResponseRedirect(reverse('users.views.detail', args=[profile.slug]))
def add_review(request, game_id): game = get_object_or_404(Game, pk=game_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name = request.user.username review = Review() review.game = game review.user_name = user_name review.rating = rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() """Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button.""" return HttpResponseRedirect(reverse('game_detail', args=(game.id,))) return render(request, 'game_detail.html', {'game': game, 'form': form})
def create_review(request, trail_id): if request.method == 'POST': if request.user.is_authenticated(): if request.POST.get('review_text') != '': review = Review() review.review_text = request.POST.get('review_text') review.user = request.user review.trail = get_object_or_404(Trail, pk=trail_id) review.save() return HttpResponseRedirect('/trail/%s' % str(trail_id)) else: messages.add_message(request, messages.WARNING, 'No comment text was provided') return HttpResponseRedirect('/trail/%s/' % str(trail_id)) return render(request, 'trails/create_review.html', {'trail_id':trail_id, 'form':form})
def test_review_replies(self): """ Make sure that developer replies are not returned as if they were original reviews. """ addon = Addon.objects.get(id=3615) u = UserProfile.objects.get(pk=2519) version = addon.current_version new_review = Review(version=version, user=u, rating=2, body="hello") new_review.save() new_reply = Review(version=version, user=addon.authors.all()[0], reply_to=new_review, rating=2, body="my reply") new_reply.save() review_list = [r.pk for r in addon.reviews] assert new_review.pk in review_list, "Original review must show up in review list." assert new_reply.pk not in review_list, "Developer reply must not show up in review list."
def test_review_replies(self): """ Make sure that developer replies are not returned as if they were original reviews. """ addon = Addon.objects.get(id=3615) u = UserProfile.objects.get(pk=2519) version = addon.get_current_version() new_review = Review(version=version, user=u, rating=2, body='hello') new_review.save() new_reply = Review(version=version, user=u, reply_to=new_review, body='my reply') new_reply.save() review_list = [r.pk for r in u.reviews] eq_(len(review_list), 1) assert new_review.pk in review_list, ( 'Original review must show up in review list.') assert new_reply.pk not in review_list, ( 'Developer reply must not show up in review list.')
def run(): libraries = connections["old"].cursor() cursor = connections["old"].cursor() # Delete existing courses print "Removing existing libraries..." Library.objects.all().delete() print "Creating libraries..." cached_users = dict([(profile.principal_id, profile.user) for profile in Profile.objects.select_related().all()]) cached_users["zope.manager"] = admin class_id = 101 cursor.execute("SELECT object_id, id FROM _intids WHERE class_id = %s", [class_id]) intids = dict(cursor.fetchall()) tags_dict = {} cursor.execute("SELECT * FROM _tags") for item, principal, name, timestamp in cursor.fetchall(): if item not in tags_dict: tags_dict[item] = [] if principal in cached_users: tags_dict[item].append((name, cached_users[principal], timestamp)) rating_dict = {} cursor.execute("SELECT * FROM _overall_rating WHERE id = 'overall_rating'") for item, id, principal, value, timestamp in cursor.fetchall(): if item not in rating_dict: rating_dict[item] = [] if principal in cached_users: rating_dict[item].append((int(value), cached_users[principal], timestamp)) reviews_dict = {} cursor.execute("SELECT * FROM _reviews") for item, principal, text, timestamp in cursor.fetchall(): if item not in reviews_dict: reviews_dict[item] = [] if principal in cached_users: reviews_dict[item].append((text, cached_users[principal], timestamp)) saved_items_dict = {} cursor.execute("SELECT * FROM _bookmarks") for item, principal, timestamp in cursor.fetchall(): if item not in saved_items_dict: saved_items_dict[item] = [] if principal in cached_users: saved_items_dict[item].append((cached_users[principal], timestamp)) creators = {} cursor.execute("SELECT * FROM _ownership WHERE class_id = %s", [class_id]) for object_id, class_id, principal_id in cursor.fetchall(): if principal_id in cached_users: creators[object_id] = cached_users[principal_id] else: creators[object_id] = admin created_dict = {} cursor.execute("SELECT * FROM _dublincore WHERE class_id = %s AND property = %s AND qualified = %s", [class_id, "Date", "Created"]) for id, object_id, class_id, property, qualified, value in cursor.fetchall(): created_dict[object_id] = parse(value) modified_dict = {} cursor.execute("SELECT * FROM _dublincore WHERE class_id = %s AND property = %s AND qualified = %s", [class_id, "Date", "Modified"]) for id, object_id, class_id, property, qualified, value in cursor.fetchall(): modified_dict[object_id] = parse(value) workflow_state_dict = {} cursor.execute("SELECT object_id, state FROM _workflowstates WHERE class_id = %s", [class_id, ]) for object_id, state in cursor.fetchall(): workflow_state_dict[object_id] = state libraries.execute("SELECT * FROM libraries") total_items = libraries.rowcount cnt = 0 for id, name, title, description, content_creation_date, authors, \ author_emails, author_countries, remote_url, keywords, \ tech_requirements, general_subjects, grade_levels, languages, \ geographic_relevance, institution, collection, material_types, \ media_formats, curriculum_standards, is_homepage, iskme_id, cksum, native_id, \ license_url, license_name, license_image, license_description, \ copyright_holder, in_rss, rss_description, rss_datetime, is_featured, \ publication_time, _searchindex, cou_bucket, tags in libraries.fetchall(): if "audio-lectures" in material_types: continue cnt += 1 creator = creators[id] try: library = Library(id=id, slug=force_unicode(name), title=force_unicode(title), abstract=force_unicode(description), content_creation_date=content_creation_date, url=force_unicode(remote_url), tech_requirements=force_unicode(tech_requirements), institution=institution and Institution.objects.get_or_create(name=force_unicode(institution))[0] or None, collection=collection and Collection.objects.get_or_create(name=force_unicode(collection))[0] or None, license=License.objects.get_or_create(url=force_unicode(license_url), name=force_unicode(license_name), image_url=force_unicode(license_image), description=force_unicode(license_description), copyright_holder=force_unicode(copyright_holder))[0], curriculum_standards=curriculum_standards, is_homepage=bool(is_homepage), provider_id=force_unicode(native_id), in_rss=in_rss, rss_description=rss_description, rss_timestamp=rss_datetime, featured=is_featured, published_on=publication_time, creator=creator, created_on=created_dict[id], modified_on=modified_dict[id], workflow_state=workflow_state_dict[id], ) library.save() except DatabaseError: import pprint pprint.pprint(dict([(k, len(v)) for k, v in locals().items() if isinstance(v, basestring) and len(v) > 100])) raise for i, author_name in enumerate(authors): author_name = force_unicode(author_name).replace(u'"', u"") author_email = len(author_emails) > i and force_unicode(author_emails[i]) or u"" author_country = len(author_countries) > i and Country.objects.get(slug=force_unicode(author_countries[i])) or None library.authors.add(Author.objects.get_or_create(name=author_name, email=author_email, country=author_country)[0]) for o in general_subjects: library.general_subjects.add(GeneralSubject.objects.get(slug=o)) for o in grade_levels: library.grade_levels.add(GradeLevel.objects.get(slug=o)) cleaned_keywords = cleanup_keywords(force_unicode(keywords)) for o in cleaned_keywords: library.keywords.add(Keyword.objects.get_or_create(name=o)[0]) for o in languages: library.languages.add(Language.objects.get(slug=o)) for o in geographic_relevance: library.geographic_relevance.add(GeographicRelevance.objects.get(slug=o)) for o in material_types: library.material_types.add(LibraryMaterialType.objects.get(slug=o)) for o in media_formats: library.media_formats.add(MediaFormat.objects.get(slug=o)) int_id = intids[id] if int_id in tags_dict: for name, user, timestamp in tags_dict[int_id]: tag = Tag(object_id=id, content_type=content_type, name=force_unicode(name), user=user) tag.timestamp = timestamp tag.save() if int_id in rating_dict: for value, user, timestamp in rating_dict[int_id]: rating = Rating(object_id=id, content_type=content_type, value=value, user=user) rating.timestamp = timestamp rating.save() if int_id in reviews_dict: for text, user, timestamp in reviews_dict[int_id]: review = Review(object_id=id, content_type=content_type, text=force_unicode(text), user=user) review.timestamp = timestamp review.save() if int_id in saved_items_dict: for user, timestamp in saved_items_dict[int_id]: saved_item = SavedItem(object_id=id, content_type=content_type, user=user) saved_item.timestamp = timestamp saved_item.save() if cnt % 100 == 0: print "%i of %i" % (cnt, total_items) reindex_materials() print "Done!"
def business_get(request): """ Returns the business errors ====== * status 404 - if the business can't be found returns ======= /businesses/<id>?reviews=true :: { "rating": 5, "modified": "2015-08-10T00:20:14.370000", "address": { "street1": "Time Square", "postal_code": "", "street2": "", "city": "New York", "state": "NY" }, "id": "55c7ee3efad9b43993d7190f", "location": [ -73.985131, 40.758895 ], "reviews": [ { "rating": 5, "modified": "2015-08-10T00:20:17.753000", "id": "55c7ee41fad9b43993d71919", "user_id": "55c7ee3dfad9b43993d7190e", "reviewed_id": "55c7ee3efad9b43993d7190f", "tags": [ "awesome" ], "text": "This is awesome.", "created": "2015-08-10T00:20:17.753000", "reviewed_collection": "businesses" } ], "tags": [ "awesome" ], "name": "Time Square", "created": "2015-08-10T00:20:13.760000" } """ business_id = request.matchdict['business_id'] include_reviews = request.validated['reviews'] business = Business.get_by_id(business_id) # a light redis check is an example of how queries can be further optimized if include_reviews: cache_key = 'business:{}:reviews-true'.format(business_id) else: cache_key = 'business:{}:reviews-false'.format(business_id) cached = redis_cache.get(cache_key) if cached and business: response_body = cached elif business: response_body = business.toJSON() if include_reviews: response_body['reviews'] = Review.reviews_for_reviewed(business.collection, business.id) response_body = json.dumps(response_body, cls=ComplexEncoder) redis_cache.set(cache_key, response_body) logger.debug('Retrieved business:{}'.format(business.id)) else: logger.debug('Failed to retrieve business:{}'.format(business_id)) request.response.status_int = 404 response_body = json.dumps({ 'status': 'error', 'message': 'failed to find business' }) request.response.body = response_body request.response.content_type = 'application/json' return request.response
from questions.models import Quiz, Sitting from reviews.models import Review quizzes = Quiz.objects.filter(id__in=[19]) sitting = Sitting.objects.get(pk=7) # peer reviews with open('/srv/jibupro/documentation/customers/galana2016.csv', "rb") as ifile: reader = csv.reader(ifile) t = zip(reader) for i in t: try: this_user = User.objects.get(email=i[0][0]) except User.DoesNotExist: pass else: emails = [x.strip() for x in i[0][1].split(",")] reviewers = User.objects.filter(email__in=emails) for quiz in quizzes: this_review = Review(customer=quiz.customer, userprofile=this_user.userprofile, sitting=sitting, quiz=quiz) this_review.save() for person in reviewers: this_review.reviewers.add(person.userprofile) groups = this_user.userprofile.group.all() for group in groups: this_review.reviewers.add(group.manager)
def handle(self, *args, **options): u''' Implementacja generowania danych dla bazy''' gen = gen_data.Gen_data() #usuniecie danych z poprzeniej bazy danych call_command('flush', interactive=True) self.stdout.write(' ') self.stdout.write('---------------------------------------------------') self.stdout.write('|Rozpoczeto generowanie danych. |') self.stdout.write('---------------------------------------------------') self.stdout.write('generowanie:') org_units = [] employees = [] students = [] study_cycles = [] thesis_subjects = [] autorships = [] self.stdout.write('jenostki organizacyjne') #wygenerowanie jednostek organizacyjnych for unitName in gen.organizationalUnitNames: # jednostka organizacyjna katedra dziekanat org_unit = OrganizationalUnit(ldapId=gen.get_next_int(), name=unitName, #head= ) org_unit.save() org_units.append(org_unit) self.stdout.write('wygenerowanie oraz przypianie pracownikow') #przypisaie danych employees_per_unit = len(employees)/len(org_units) for unit in org_units: #wygenerowanie puli pracownikow for i in range(0, employees_per_unit): # pracownik uczelni name, surname, email, username = gen.get_next_user() user_emp = User.objects.create_user( first_name=name, email=email, last_name=surname, username=username ) user_emp.save() employee = Employee(title=gen.get_random_title(), user=user_emp, #position=, organizationalUnit=org_units[unit], ) employee.save() employees.append(employee) self.stdout.write('tematy prac') #wygenerowanie tematow prac oraz zmian for emp in employees: # zmiana stanu pracy dyplomowej (po jednej losowej zmianie_samego_tematu na temat) tssc = ThesisTopicStateChange(state=gen.choose_tuple(ThesisTopicStateChange.THESIS_SUBJECT_STATE_CHOICES)[0], #initiator=, comment="jakis wygenerowany comment", occuredAt=datetime.date.today() ) tssc.save() # temat pracy thesis_subject = ThesisTopic(#statesHistory=, # many-to-many sa wykozystywanie dopiero po save() title="wygenerowany temat pracy", description="bardzo szczegolowy opis", teamMembersLimit=gen.get_rand_int(), author=emp.user ) thesis_subject.save() thesis_subject.statesHistory.add(tssc) thesis_subjects.append(thesis_subject) self.stdout.write('cykle ksztalcenia') #wygeneruj cykle ksztalcenia for cycle in gen.study_cycles: # cykl ksztalcenia study_cycle = StudyCycle(ldapId=gen.get_next_int(), name=cycle, submissionsOpenAt = datetime.date.today(), submissionsCloseAt = datetime.date.today(), #isLdapSynced=, ) study_cycle.save() study_cycles.append(study_cycle) self.stdout.write('wygenerowanie studentow') #wygeneruj pule studentow for student_id in range(0, gen.students_count): name, surname, email, student_username = gen.get_next_user() student_userr = User.objects.create_user( first_name=name, email=email, last_name=surname, username=student_username ) student_userr.save() #Student student = Student(#studyCycles=[study_cycle], #many to many user=student_userr ) student.save() # zawsze jest dodawany pierwszy, jeden i ten sam cykl nauczania (dla prostoty) student.studyCycles.add(study_cycles[0]) students.append(student) self.stdout.write('powiazanie studentow z tematami prac') # powiaznie student - temat pracy i = 0; for ts in thesis_subjects: autorship = Authorship(state=gen.choose_tuple(Authorship.AUTHORSHIP_STATE_CHOICES)[0], thesisTopic=ts, comment="autorship comment", student=students[i], createdAt=datetime.date.today(), updatedAt=datetime.date.today() ) autorship.save() autorships.append(autorship) i++1; # inkrementacja licznika studentow self.stdout.write('losowe recenzje') #wygenerowanie losowych reenzji review_count = len(thesis_subjects)/2 # polowa prac bedzie zrecnzwana for r in range(0, review_count): #recenzja review = Review(authorType=gen.choose_tuple(Review.REVIEW_AUTHOR_TYPE_CHOICES)[0], author=employees[r], #tematow pracy jest tyle ile pracownikow a recenzji polowa tego wiec pierwsza ploowa pracownikow dokona zrecenzowania comment="Review comment", mark=gen.get_grade(), #isDone =, #attachments =, ) review.save() self.stdout.write('wygenerowanie prac') # wygeneruj tyle prac co powiazan student - temat pracy s = 0; for ash in autorships: # praca dyplomowa thesis = Thesis(authorship=ash, #isDone=, #attachments=, supervisor=employees[s], #auxiliarySupervisors=, #advisor=, #reviews=review ) s+=1; thesis.save() self.stdout.write('kryteria pracy dla studenta') # kryteria wzgledem pracy dla studntow sub_crit = SubmissionCriterion(type=gen.choose_tuple(SubmissionCriterion.CRITERION_TYPE_CHOICES)[0], label="text opisujacy" ) # para kryterium odpowiedz # sub_crit_val = nawia.SubmissionCriterionValue(criterion=sub_crit # ) self.stdout.write('jenostki zewnetrzne') # jednostka zewnetrzna org = Organization(name="organizacja zewnetrzna" ) self.stdout.write('wladze wydzialu') # wladze wydzialu authority = Authority(#role=, ) self.stdout.write('koniec.') self.stdout.write(' ') self.stdout.write('---------------------------------------------------') self.stdout.write('|Generowanie zawartosci bazy przebieglo pomyslnie.|') self.stdout.write('---------------------------------------------------')