Exemple #1
0
    def get_next_task_view(self):
        self.client.login(username="******", password="******")
        ## get the next task
        self.task_expectation.check(self)
        ## tweak the database to put a response and a review in
        response = Response(task=self.t, user=self.user, start_time=datetime.datetime.now())
        response.full_clean()
        response.save()
        review = Review(response=response, comment="I have reviewed this task.")
        review.full_clean()
        review.save()
        ## check to see if next_task now redirects to review
        ## if we actually execute the view code, we will get an error,
        ## because the task associated with the review has no result;
        ## therefore the code below is a bit hackish
        review_target = WebTarget("GET", main.views.base.next_task, statuses=(301, 302))

        def redirects_to_review(input_context, output_context):
            return "/review/next/" in output_context["__redirected_to__"]

        review_expectation = ViewExpectation(Conditions.post(redirects_to_review), review_target)
        review_expectation.check(self)
        ## tweak the database to complete the review
        review.complete = True
        review.full_clean()
        review.save()
        ## try getting the next task again
        self.task_expectation.check(self)
Exemple #2
0
def comments_create(request, post_id):
    post = Bar_code.objects.get(pk=post_id).pk
    content = request.POST.get('content')
    comment = Review(code_name_id=int(post), review_text=content)
    comment.save()

    return HttpResponseRedirect(
        reverse('main:product_detail', args=(post_id, )))
Exemple #3
0
    def handle(self, *args, **options):
        count = options["reviews"]

        ignored = 0
        # generate reviews
        for i in range(count):
            print "generate review %d" % (i + 1)
            order = random.choice(Order.objects.all())
            if not order.orderitem_set.all():
                print "ignore order: %d, it has no orderitems" % order.id
                continue
            orderitem = random.choice(order.orderitem_set.all())
            if Review.objects.filter(orderitem=orderitem).first():
                print "ignoring orderitem: %s, it has a review already" % orderitem
                ignored += 1
                continue
            r = Review()
            r.orderitem = orderitem
            r.rating = random.randint(1, 5)
            r.language = order.table.restaurant.menu.language
            r.text = random.choice(review_texts)
            r.user = order.user
            r.save()

        self.stdout.write('Successfully added %d reviews' % (count - ignored))
Exemple #4
0
def save_review_from_row(review_row):
    review= Review()
    userprofile = UserProfile.objects.get(id=review_row[1])
    sake = Product.objects.get(id=review_row[2])

    review.id = review_row[0]
    review.user = userprofile
    review.sake = sake
    review.rating = review_row[3]
    review.content = review_row[4]
    review.date = datetime.datetime.now()
    review.save()
Exemple #5
0
def task_adhoc_review(get, guts):
    if get:
        response_id = guts.parameters['response']
        response = Response.objects.get(pk=response_id)
        reviews = Review.objects.filter(response=response)
        if reviews.count() == 1:
            review = reviews[0]
        else:
            review = Review(response=response, comment="")
        task = response.task
        result = task.result
        # Tagger or merger can both view, as well as super-user
        if ((response.user != guts.user) and not (guts.user.is_superuser)
                and (result.user != guts.user)):
            return ForbiddenResponse(
                "You are not authorized to see this review.")
        project_type = get_project_type(task.project)
        task = project_type.cast(task)
        try:
            template = get_template(review.review_template)
        except NotImplementedError:
            template = task.template()
        template_data = task.template_data(review=review)
        return TemplateResponse(template, template_data)
    else:
        return ViewResponse('main:next-review')
Exemple #6
0
def create_review(request, id):
    print('inside create review method')
    print('id', id)

    # Get the user object of the person adding this review
    this_user = User.objects.get(id=request.session['userid'])

    # Get the book object of book this review is for
    this_book = Book.objects.get(id=id)

    # Create a review for this book (id)
    new_review = Review(
        text=request.POST['review'], rating=request.POST['rating'], user=this_user, book=this_book)
    new_review.save()

    return redirect('/books/'+str(this_book.id))
Exemple #7
0
    def addReview(self, professionalId, user, rating, reviewText):
        #TODO: fix js to always send a number for rating?
        # RB: Yes. But we should have this as a backup anyway.
        if rating == 'null':
            rating = 0

        items = Professional.objects.filter(pk=professionalId)
        if len(items) == 1 and user != None and not user.is_anonymous():
            professional = items[0]

            reviews = Review.objects.filter(professional=professional,
                                            user=user)
            if len(reviews) != 0:
                # Update review/rating
                review = reviews[0]
                review.rating = rating
                review.date = datetime.utcnow()
                review.text = reviewText
                print review.text, review.rating, review.date
            else:
                # Add new review/rating
                review = Review(user=user,
                                professional=professional,
                                text=reviewText,
                                rating=rating,
                                date=datetime.utcnow(),
                                karma=0)

                # Create association
                association = UserProfessional(user=user,
                                               professional=professional)
                association.save()

            review.save()

            # Create association
            association = UserProfessional(user=user, professional=items[0])
            association.save()

        return review
def save_reviews(response, business, latest_review_date):
    """
    Save reviews to database.

    :param response: Holds review data
    :param business: The business the reviews are for
    :param latest_review_date: The most recent date we fetched for reviews
    for the business
    :return: Nothing. Reviews are saved to database.
    """
    ids = response.data[0]
    ratings = response.data[1]
    publish_dates = response.data[2]
    #texts = response.data[3]

    try:
        for id, rating, publish_date in zip(ids, ratings, publish_dates):
            # Don't bother to save if the review already exists in db.
            if not Review.objects.filter(id=id).exists():
                # Quit out if the publish date is older than the last fetch date
                # since everything in the loop now will be older than the last
                # fetch date.
                if latest_review_date is not None and publish_date < latest_review_date:
                    continue
                review = Review(id=id,
                                business=business,
                                rating=rating,
                                publish_date=publish_date)
                review.save()

        # Save for in case we want to store text
        # for id, rating, publish_date, text in zip(ids, ratings, publish_dates, texts):
        #     if not Review.objects.filter(id=id).exists():
        #         if latest_review_date is not None and publish_date < latest_review_date:
        #             continue
        #         review = Review(id=id, business=business, rating=rating, publish_date=publish_date, text=text)
        #         review.save()
    except Exception as ex:
        log_exception(MODULE_NAME, inspect.currentframe().f_code.co_name, ex)
Exemple #9
0
def create(request):
    # Get the user object for the logged in user
    this_user = User.objects.get(id=request.session['userid'])

    # Add new book and review
    print(request.POST)

    if request.POST['author_name'] != '':
        # Check if that author name is already in the database
        # ...And if it is, then use the existing record, do not add a new author
        authors_found = Author.objects.filter(
            name=request.POST['author_name'].strip())
        if authors_found:
            this_author = authors_found[0]
        else:
            # Adding a new author
            this_author = Author(name=request.POST['author_name'].strip())
            this_author.save()
            print('new_author.name', this_author.name)

    else:
        print('Using an author from select list')
        # get the user pulled from the select menu
        this_author = Author.objects.get(id=request.POST['author_list'])
        print('this_author', this_author.name, this_author.id)

    # Add the book
    new_book = Book(title=request.POST['title'],
                    author=this_author, user=this_user)
    new_book.save()

    # Add the review
    new_review = Review(
        text=request.POST['review'], rating=request.POST['rating'], book=new_book, user=this_user)
    new_review.save()

    return redirect('/books/'+str(new_book.id))
Exemple #10
0
def save_reviews(response, business, latest_review_date):
    """
    Save reviews to database.

    :param response: Holds review data
    :param business: The business the reviews are for
    :param latest_review_date: The most recent date we fetched for reviews
    for the business
    :return: Nothing. Reviews are saved to database.
    """
    ids = response.data[0]
    ratings = response.data[1]
    publish_dates = response.data[2]
    #texts = response.data[3]

    try:
        for id, rating, publish_date in zip(ids, ratings, publish_dates):
            # Don't bother to save if the review already exists in db.
            if not Review.objects.filter(id=id).exists():
                # Quit out if the publish date is older than the last fetch date
                # since everything in the loop now will be older than the last
                # fetch date.
                if latest_review_date is not None and publish_date < latest_review_date:
                    continue
                review = Review(id=id, business=business, rating=rating, publish_date=publish_date)
                review.save()

        # Save for in case we want to store text
        # for id, rating, publish_date, text in zip(ids, ratings, publish_dates, texts):
        #     if not Review.objects.filter(id=id).exists():
        #         if latest_review_date is not None and publish_date < latest_review_date:
        #             continue
        #         review = Review(id=id, business=business, rating=rating, publish_date=publish_date, text=text)
        #         review.save()
    except Exception as ex:
        log_exception(MODULE_NAME, inspect.currentframe().f_code.co_name, ex)
Exemple #11
0
def add_review(request, slug):

    user = request.user
    userprofile = UserProfile.objects.get(user=user)
    sake = get_object_or_404(Product, slug=slug)
    form = ReviewForm(request.POST, instance=userprofile)

    try:
        review_check = Review.objects.get(user=userprofile, sake=sake)

    except Review.DoesNotExist:
        pass
    else:
        messages.info(request,
                      'You have already written a review for this sake.')
        return HttpResponseRedirect(reverse('product', args=(slug, )))

    if request.method == 'POST':
        form = ReviewForm(data=request.POST, instance=userprofile)
        if form.is_valid():
            review = Review()
            content = form.cleaned_data['content']
            rating = form.cleaned_data['rating']
            review.user = userprofile
            review.content = content
            review.rating = rating
            review.date = datetime.now()
            review.sake = sake
            review.save()
            form.save()
            update_clusters(is_new_user=False)
            messages.success(request, "Thank you for your review!")
            return HttpResponseRedirect(reverse('product', args=(slug, )))

    return render(request, 'reviews/add_review.html', {
        'sake': sake,
        'form': form
    })
Exemple #12
0
def task_view(get, guts, task_id):
    """View a given task ID or submit a response to it; in either
    case, this should dispatch appropriately based on the task's
    type."""
    import main.views.base

    task = Task.objects.get(pk=task_id)
    project_type = type_list[task.project.type]
    task = project_type.cast(task)
    try:
        wip = WorkInProgress.objects.get(task=task, user=guts.user)
    except WorkInProgress.DoesNotExist:
        if task.project.auto_review:
            try:
                ## Tasks in auto-review projects have a kludgey workflow:
                ## the task is responsible for noticing that it is in an
                ## auto-review project and adjusting the output of template()
                ## and template_data accordingly.
                ## When GETting the page, if a Response object already exists, then
                ## the output should be appropriate for displaying a review.
                auto_review = AutoReview.objects.get(task=task, user=guts.user)
                if get:
                    ## If the Task subclass has not been retrofitted to handle
                    ## auto-review projects, then this line will throw an exception
                    ## "TypeError: ... unexpected keyword argument 'auto_review_user'"
                    return TemplateResponse(
                        task.template(),
                        task.template_data(auto_review_user=guts.user))
                else:
                    ## NOTE: does the downcasting of task screw this query up?
                    response_query = Response.objects.filter(user=guts.user,
                                                             task=task)
                    if not response_query.exists():
                        ## No response?  Ask the task to make one!
                        kwargs = {
                            "user": guts.user,
                            "task": task,
                            "start_time": auto_review.start_time,
                        }
                        task.handle_response(guts, **kwargs)
                        ## (Note that this code path does NOT update the task's
                        ## completed_assignments field, because auto-review projects
                        ## do not have a limit on how many responses they can have.)
                        ##
                        ## And then GET this page again, so the user can see the review.
                        return ViewResponse('main:view-task', task_id)
                    else:
                        ## The user must have clicked the "I read this review" button.
                        auto_review.end_time = timezone.now()
                        auto_review.full_clean()
                        auto_review.save()
                        return ViewResponse('main:next-task')
            except AutoReview.DoesNotExist:
                ## fall through to the case below, since an admin is allowed to
                ## look at someone else's auto-review
                pass
        ## an admin can look at any task, but not even an admin
        ## can submit a response or result to a task without getting a WIP first
        if not (task.viewable_by(guts.user) and get):
            return ForbiddenResponse("You are not allowed to view %s." %
                                     six.text_type(task))
    if get:
        return TemplateResponse(task.template(), task.template_data())
    else:
        ## TODO: if we successfully make handle_response a method of the task,
        ## then we don't have to pass the task in kwargs
        kwargs = {
            "user": guts.user,
            "task": task,
            "start_time": wip.start_time
        }
        try:
            task.handle_response(guts, **kwargs)
            if task.completed:
                if 'review_user' in guts.parameters:
                    users = guts.parameters.getlist('review_user')
                    for user in users:
                        user_obj = User.objects.get(pk=user)
                        comment = guts.parameters.get("comment_%s" % user, "")
                        rev = Review(
                            response=task.response_set.get(user=user_obj),
                            comment=comment,
                        )
                        rev.full_clean()
                        rev.save()
            else:
                task.completed_assignments = task.completed_assignments + 1
                task.full_clean()
                task.save()
            wip.delete()
            if 'stop_working' in guts.parameters:
                return ViewResponse('main:home')
            else:
                return ViewResponse('main:next-task')
        except MultiValueDictKeyError:
            ## translate the MultiValueDict into a list of (key, list) pairs
            params = guts.parameters.lists()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb_info = traceback.extract_tb(exc_traceback)
            template = get_template("parameter-error-in-task.html")
            context = {
                "task": str(task),
                "params": params,
                "exc_value": exc_value,
                "traceback": tb_info,
            }
            guts.log_error("Bad form? " + repr(context))
            return TemplateResponse(template, context, status=500)
Exemple #13
0
def task_view(get, guts, task_id):
    """View a given task ID or submit a response to it; in either
    case, this should dispatch appropriately based on the task's
    type."""
    import main.views.base
    task = Task.objects.get(pk=task_id)
    project_type = type_list[task.project.type]
    task = project_type.cast(task)
    try:
        wip = WorkInProgress.objects.get(task=task, user=guts.user)
    except WorkInProgress.DoesNotExist:
        if task.project.auto_review:
            try:
                ## Tasks in auto-review projects have a kludgey workflow:
                ## the task is responsible for noticing that it is in an
                ## auto-review project and adjusting the output of template()
                ## and template_data accordingly.
                ## When GETting the page, if a Response object already exists, then
                ## the output should be appropriate for displaying a review.
                auto_review = AutoReview.objects.get(task=task, user=guts.user)
                if get:
                    ## If the Task subclass has not been retrofitted to handle
                    ## auto-review projects, then this line will throw an exception
                    ## "TypeError: ... unexpected keyword argument 'auto_review_user'"
                    return TemplateResponse(task.template(),
                                            task.template_data(auto_review_user=guts.user))
                else:
                    ## NOTE: does the downcasting of task screw this query up?
                    response_query = Response.objects.filter(user=guts.user,
                                                             task=task)
                    if not response_query.exists():
                        ## No response?  Ask the task to make one!
                        kwargs = {"user": guts.user,
                                  "task": task,
                                  "start_time": auto_review.start_time}
                        task.handle_response(guts, **kwargs)
                        ## (Note that this code path does NOT update the task's
                        ## completed_assignments field, because auto-review projects
                        ## do not have a limit on how many responses they can have.)
                        ##
                        ## And then GET this page again, so the user can see the review.
                        return ViewResponse(task_view, task_id)
                    else:
                        ## The user must have clicked the "I read this review" button.
                        auto_review.end_time = datetime.datetime.now()
                        auto_review.full_clean()
                        auto_review.save()
                        return ViewResponse(main.views.base.next_task)
            except AutoReview.DoesNotExist:
                ## fall through to the case below, since an admin is allowed to
                ## look at someone else's auto-review
                pass
        ## an admin can look at any task, but not even an admin
        ## can submit a response or result to a task without getting a WIP first
        if not (task.viewable_by(guts.user) and get):
            return ForbiddenResponse(u"You are not allowed to view %s" % unicode(task))
    if get:
        return TemplateResponse(task.template(), task.template_data())
    else:
        ## TODO: if we successfully make handle_response a method of the task,
        ## then we don't have to pass the task in kwargs
        kwargs = {"user": guts.user,
                  "task": task,
                  "start_time": wip.start_time}
        try:
            task.handle_response(guts, **kwargs)
            if task.completed:
                if 'review_user' in guts.parameters:
                    users = guts.parameters.getlist('review_user')
                    for user in users:
                        user_obj = User.objects.get(pk=user)
                        comment = guts.parameters.get("comment_%s" % user, "")
                        rev = Review(response=task.response_set.get(user=user_obj), comment=comment)
                        rev.full_clean()
                        rev.save()
            else:
                task.completed_assignments = task.completed_assignments + 1
                task.full_clean()
                task.save()
            wip.delete()
            if 'stop_working' in guts.parameters:
                return ViewResponse(main.views.base.home)
            else:
                return ViewResponse(main.views.base.next_task)
        except MultiValueDictKeyError:
            ## translate the MultiValueDict into a list of (key, list) pairs
            params = guts.parameters.lists()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb_info = traceback.extract_tb(exc_traceback)
            template = get_template("parameter-error-in-task.html")
            context = {"task": str(task), "params": params,
                       "exc_value": exc_value, "traceback": tb_info}
            guts.log_error("Bad form? " + repr(context))
            return TemplateResponse(template, context, status=500)
Exemple #14
0
def main():
    reviews = json.loads(open("reviews.json", "r").read())

    Review.objects.filter(is_crawled=True).delete()
    total_added = 0
    for review in reviews:
        code = review["course"]
        course_query = CourseCode.objects.filter(code=code)
        if course_query.exists():
            r = Review()
            r.course = course_query[0].course
            r.rating = review["rating"]
            r.grade = review["grade"]
            r.text = review["text"].replace("<div>", "").replace("</div>", "")
            r.is_crawled = True
            r.created_at = str_to_timestamp(review["created_at"])
            r.updated_at = str_to_timestamp(review["updated_at"])
            r.author = DEFAULT_USER
            r.save()
            total_added += 1
            if total_added % 50 == 0:
                print "Added %s reviews" % total_added
Exemple #15
0
    def populate_test_reviews(self):
        robert = User(name="Robert", external_id=1, email="*****@*****.**")
        robert.save()

        josh = Professional.objects.get(pk=1)
        josh_r1 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Raging Robert",
                         professional=josh,
                         text="I hate this guy",
                         rating="0.5",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r2 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Angry Robert",
                         professional=josh,
                         text="Terrible",
                         rating="1",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r3 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Mad Robert",
                         professional=josh,
                         text="Very bad",
                         rating="1.5",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r4 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Disappointed Robert",
                         professional=josh,
                         text="Bad",
                         rating="2",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r5 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Unimpressed Robert",
                         professional=josh,
                         text="Meh",
                         rating="2.5",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r6 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Placated Robert",
                         professional=josh,
                         text="Not bad",
                         rating="3",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r7 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Pleased Robert",
                         professional=josh,
                         text="Okay",
                         rating="3.5",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r8 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Happy Robert",
                         professional=josh,
                         text="Good",
                         rating="4",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r9 = Review(user=User.objects.get(pk=1),
                         userDisplayName="Ecstatic Robert",
                         professional=josh,
                         text="Great",
                         rating="4.5",
                         date=datetime.utcnow(),
                         karma=1)
        josh_r10 = Review(user=User.objects.get(pk=1),
                          userDisplayName="Blown-Away Robert",
                          professional=josh,
                          text="ZOMGAMAZING!!",
                          rating="5",
                          date=datetime.utcnow(),
                          karma=1)
        josh_r1.save()
        josh_r2.save()
        josh_r3.save()
        josh_r4.save()
        josh_r5.save()
        josh_r6.save()
        josh_r7.save()
        josh_r8.save()
        josh_r9.save()
        josh_r10.save()
Exemple #16
0
    def get_next_task_view(self):
        self.client.login(username="******", password="******")
        ## get the next task
        self.task_expectation.check(self)
        ## tweak the database to put a response and a review in
        response = Response(task=self.t,
                            user=self.user,
                            start_time=timezone.now())
        response.full_clean()
        response.save()
        review = Review(response=response,
                        comment="I have reviewed this task.")
        review.full_clean()
        review.save()
        ## check to see if next_task now redirects to review
        ## if we actually execute the view code, we will get an error,
        ## because the task associated with the review has no result;
        ## therefore the code below is a bit hackish
        review_target = WebTarget("GET",
                                  main.views.base.next_task,
                                  statuses=(301, 302))

        def redirects_to_review(input_context, output_context):
            return "/review/next/" in output_context["__redirected_to__"]

        review_expectation = ViewExpectation(
            Conditions.post(redirects_to_review), review_target)
        review_expectation.check(self)
        ## tweak the database to complete the review
        review.complete = True
        review.full_clean()
        review.save()
        ## try getting the next task again
        self.task_expectation.check(self)
 def create(self, validated_data):
     review = Review(**validated_data)
     print(validated_data)
     review.save()
     return review
Exemple #18
0
prop2.save()

rating1 = Rating(score=1)
rating1.save()
rating2 = Rating(score=2)
rating2.save()
rating3 = Rating(score=3)
rating3.save()
rating4 = Rating(score=4)
rating4.save()
rating5 = Rating(score=5)
rating5.save()

review1 = Review(
    rating=rating1,
    user='******',
    description=
    'Very poor experience. The accomodation provided lacked general hygiene. Food was OK though, I just wish there was more.'
)
review1.save()

review2 = Review(
    rating=rating5,
    user='******',
    description=
    'Exceptional stay at this accomodation! The host was friendly and the room as well equipped. Highly Recommended!'
)
review2.save()

review3 = Review(
    rating=rating4,
    user='******',