コード例 #1
0
def show_product_view(request, section_slug, product_slug):
    template = 'app/phone.html'
    try:
        section = Section.objects.get(slug=section_slug)
        product_data = Product.objects.prefetch_related('reviews').get(
            section=section, slug=product_slug)

        if request.method == 'POST':
            form = ReviewForm(request.POST)
            if form.is_valid():
                text = form.cleaned_data['description']
                rating = form.cleaned_data['mark']
                author = form.cleaned_data['name']
                new_review = Review.objects.create(text=text,
                                                   rating=rating,
                                                   author=author,
                                                   product=product_data)
                ReviewProductRelation.objects.create(product=product_data,
                                                     review=new_review)
                form = ReviewForm({'name': request.user.first_name})
        else:
            form = ReviewForm({'name': request.user.first_name})
        reviews = product_data.reviews.all().order_by('-id')
        context = {
            'product_data': product_data,
            'reviews': reviews,
            'form': form
        }
    except ObjectDoesNotExist:
        context = {}

    return render(request, template, context)
コード例 #2
0
ファイル: views.py プロジェクト: sheeshmohsin/moviereviews
def movie(request, pk):
    if request.method == 'POST':
        movie = Movie.objects.get(pk=pk)
        form_obj = ReviewForm(request.POST)
        if form_obj.is_valid():
            db_obj = form_obj.save(commit=False)
            db_obj.movie = movie
            if request.user.is_authenticated():
                db_obj.added_by = request.user
            db_obj.save()
            pk_value = db_obj.pk
            return HttpResponseRedirect(reverse('movie_detail', args=(pk, )))
        else:
            reviews = paginate_reviews(request, movie)
            return render(request, 'movie.html', {
                'movie': movie,
                'form': form,
                'reviews': reviews
            })
    elif request.method == 'GET':
        movie = Movie.objects.get(pk=pk)
        form = ReviewForm()
        reviews = paginate_reviews(request, movie)
        return render(request, 'movie.html', {
            'movie': movie,
            'form': form,
            'reviews': reviews
        })
    else:
        raise Http404("Request method type not defined")
コード例 #3
0
def good_view(request):
    sections = Section.objects.all()
    template = 'app/good.html'
    good = ''
    reviews = ''

    review_left = request.COOKIES.get('review_left')
    if review_left:
        review_left = review_left.replace(r"'", r'"')
        review_left = json.loads(review_left)
        review_list = review_left["you_reviews"]
    else:
        review_list = []
        review_left = {"you_reviews": review_list}
    if request.method == 'POST':
        fb_id = request.GET.get('feedback')
        response = HttpResponseRedirect(f'/good/?id={fb_id}')
        if fb_id and not fb_id in review_list:
            review_form = ReviewForm(request.POST or None)
            if review_form.is_valid():
                name = review_form.cleaned_data.get('name')
                text = review_form.cleaned_data.get('text')
                rating = review_form.cleaned_data.get('rating')
                product = Product.objects.filter(id=int(fb_id))[0]
            new_feedback = Review(name=name,
                                  text=text,
                                  rating=rating,
                                  product=product)
            new_feedback.save()
            review_list.append(int(fb_id))
            print('review_list=', review_list)
            review_left["you_reviews"] = review_list
            review_left = json.dumps(review_left)
            response.set_cookie('review_left', review_left)
            return response

    id = request.GET.get('id')
    if id:
        good = Product.objects.filter(id=int(id))[0]
        if good:
            reviews = Review.objects.filter(product=int(id))
    if good.id in review_left['you_reviews']:
        review_left = True
    else:
        review_left = False
    print('review_left=', review_left, type(review_left))
    form = ReviewForm()
    context = {
        'sections': sections,
        'good': good,
        'reviews': reviews,
        'review_left': review_left,
        'form': form,
    }
    return render(request, template_name=template, context=context)
コード例 #4
0
def main_add_review(asin=None):
    product = get_object_or_404(Product, asin == Product.asin)
    return render_template(
        'review_add.html',
        product=product,
        form=ReviewForm(request.form)
    )
コード例 #5
0
def handle_review(id):

    review = Review.query.filter(Review.id == id).first()

    if review is not None:

        if request.method == "DELETE":
            db.session.delete(review)
            db.session.commit()
            return {"message": "Review deleted"}, 200
        if request.method == "PATCH":

            form = ReviewForm()
            form['csrf_token'].data = request.cookies['csrf_token']

            if form.validate_on_submit():
                # form populate obj
                review.product_id = request.form.get("product_id")
                review.user_id = request.form.get("user_id")
                review.content = request.form.get("content")
                review.roast_rating = request.form.get("roast_rating")
                review.updated_at = datetime.now()

                db.session.add(review)
                db.session.commit()
                return review.to_dict(), 200

            return {
                "errors": validation_errors_to_error_messages(form.errors)
            }, 400

    return {"error": "Review does not exist"}, 404
コード例 #6
0
def addReview():
    """
    Posts a New Review
    """
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print('Request', request.json)
    print('Form', form.data)
    if form.validate_on_submit():
        print('Current User', current_user)
        review = Review(user_id=(form.data['user']),
                        restaurant_id=(form.data['restaurant']),
                        body=form.data['body'],
                        rating=(form.data['rating']),
                        bags=form.data['bags'],
                        utensils=form.data['utensils'],
                        napkins=form.data['napkins'],
                        cups=form.data['cups'],
                        bowls=form.data['bowls'],
                        straws=form.data['straws'],
                        created=datetime.datetime.now(),
                        updated=datetime.datetime.now())
        print('Review', review)
        db.session.add(review)
        db.session.commit()
        return review.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
コード例 #7
0
def create_review():
    """
    Creates an review.
    """
    form = ReviewForm()
    print(request.get_json())
    # Get the csrf_token from the request cookie and put it into the
    # form manually to validate_on_submit can be used
    form['csrf_token'].data = request.cookies['csrf_token']
    print('<<<<<<<<<<<< csrf', form['csrf_token'].data)
    if form.validate_on_submit():
        print('validated form')
        app_id = form.data['application_id']
        first_rev = Review.query.filter(
            Review.application_id == app_id).first()
        review = Review(writer_id=form.data['writer_id'],
                        reviewee_id=form.data['reviewee_id'],
                        application_id=form.data['application_id'],
                        content=form.data['content'],
                        score=form.data['score'])
        db.session.add(review)
        db.session.commit()
        if first_rev:
            first_rev.response_id = review.id
            db.session.add(first_rev)
            db.session.commit()
        rev = review.to_dict()
        order_id = rev['order_id']
        order = Order.query.filter(Order.id == order_id).first()
        order.status = "Complete"
        db.session.add(order)
        db.session.commit()
        return review.to_dict()
    return 'invalid form'
コード例 #8
0
def movie_details(id):
    m = Movie.query.get_or_404(id)
    reviews = Review.query\
        .with_entities(User.username, Review.grade, Review.feelings, Review.thoughts,
            Review.timestamp, Review.user_id, User.image)\
        .filter(Review.movie_id == id)\
        .join(User)\
        .limit(4)\
        .all()
    form = ReviewForm()
    if form.validate_on_submit():
        review = Review(grade=form.grade.data,
                        thoughts=form.thoughts.data,
                        feelings=form.feelings.data,
                        user_id=current_user.id,
                        movie_id=id)
        db.session.add(review)
        db.session.commit()
        flash('Review sent succesfully')
        return redirect(url_for('main.movie_details', id=id))
    return render_template('movie_details.html',
                           title='movie_details',
                           movie=m,
                           reviews=reviews,
                           form=form)
コード例 #9
0
ファイル: routes.py プロジェクト: bstanton773/MoviesFinal
def review(movieId):
    if current_user.is_anonymous:
        return redirect(url_for('login'))
    form = ReviewForm()
    if form.validate_on_submit():
        if len(form.comment.data) == 0:
            rating = Reviews(user_id=current_user.id,
                             movie_id=movieId,
                             rating=form.rating.data)
            db.session.add(rating)
            db.session.commit()
        else:
            rating_comment = Reviews(user_id=current_user.id,
                                     movie_id=movieId,
                                     rating=form.rating.data,
                                     comment=form.comment.data)
            db.session.add(rating_comment)
            db.session.commit()
    movie = Movies.query.filter_by(movieId=movieId).first()
    comments = Reviews.query.filter_by(movie_id=movieId).join(
        Movies, Reviews.movie_id == Movies.movieId).join(
            User,
            Reviews.user_id == User.id).add_columns(Movies.title,
                                                    Movies.movieId,
                                                    Reviews.comment,
                                                    User.username).all()
    return render_template('review.html',
                           movie=movie,
                           title='Review',
                           form=form,
                           comments=comments)
コード例 #10
0
 def get(self, request, pk) :
     app = App.objects.get(app_id=pk)
     review_form = ReviewForm()
     reviews = app.review_set.all().order_by('-date_updated')
     reviews_cnt = len(reviews)
     ctx = {'app': app, 'review_form': review_form, 'reviews': reviews, 'reviews_cnt': reviews_cnt, 'user': request.user}
     return render(request, self.template_name, ctx)
コード例 #11
0
ファイル: routes.py プロジェクト: guryaniv/book_reviews
def book_page(isbn):
    """page with the book's details and reviews, with an option to leave a new review"""
    # Make sure book exists
    book = Book.query.get(isbn)
    if book is None:
        flash("No such book. Search again.")
        return redirect(url_for('index'))
    form = ReviewForm()
    success = None
    if form.validate_on_submit():
        score = int(form.score.data)
        text = form.text.data
        user_name = current_user.username
        success = book.add_review(user=user_name, score=score, text=text)
        if not success:
            flash("You can only rate a book once.")
        else:
            flash("Your review was added.")
    # Get all book reviews
    reviews = book.reviews
    return render_template("book.html",
                           book=book,
                           reviews=reviews,
                           form=form,
                           title="Book Page",
                           success=success)
コード例 #12
0
def makeReview(id):
    form = ReviewForm()
    print("successfulqwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww post",
          form.data)
    form['csrf_token'].data = request.cookies['csrf_token']
    print(",,,,,,,,,,,,,,,,,,,,,,,,,,,", form['csrf_token'].data)
    print("the return boy", form.data)
    print("the return boy", form.data['reviews'])
    print("the return boy", form.data['ratings'])
    reviewData = form.data['reviews']
    ratingData = form.data['ratings']

    existing_Product = UserProduct.query.filter_by(users_id=current_user.id,
                                                   products_id=id).first()
    print("existddddddddddddddddddddddddddddddddddddddddddddddddddin product",
          existing_Product.reviews)
    if existing_Product:
        existing_Product.reviews = reviewData,
        existing_Product.ratings = ratingData
        db.session.add(existing_Product)
        db.session.commit()

    if form.validate_on_submit():
        review = UserProduct(users_id=current_user.id,
                             products_id=int(id),
                             reviews=reviewData,
                             ratings=ratingData)
        db.session.add(review)
        db.session.commit()
        return UserProduct.to_dict_product(review)
    return "Bad Data"
コード例 #13
0
ファイル: review.py プロジェクト: nellace/ustc-course
def new_review(course_id):
    course = Course.query.get(course_id)
    if not course:
        abort(404)
    user = current_user
    review = Review.query.filter_by(course=course, author=user).first()
    if not review:
        review = Review()
        review.course = course
        review.author = user
        is_new = True
    else:
        is_new = False

    message = ''
    form = ReviewForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            # check validity of term
            if str(form.term.data) not in course.term_ids:
                abort(404)

            if form.is_mobile.data:
                form.content.data = markdown.markdown(form.content.data)
            form.content.data, mentioned_users = editor_parse_at(form.content.data)
            form.content.data = sanitize(form.content.data)
            form.populate_obj(review)

            if is_new:
                review.add()
                for user in set(current_user.followers + course.followers + course.joined_users):
                    user.notify('review', review, ref_display_class='Course')
                # users can only receive @ notifications for new reviews
                for user in mentioned_users:
                    user.notify('mention', review)
            else:
                review.save()
            return redirect(url_for('course.view_course',course_id=course_id))
        else: # invalid submission, try again
            if form.content.data:
                review.content = sanitize(form.content.data)
            if form.difficulty.data:
                review.difficulty = form.difficulty.data
            if form.homework.data:
                review.homework = form.homework.data
            if form.gain.data:
                review.gain = form.gain.data
            if form.rate.data:
                review.rate = form.rate.data
            message = '提交失败,请编辑后重新提交!'

    polls = [
        {'name': 'difficulty', 'display': '课程难度', 'options': ['简单', '中等', '困难'] },
        {'name': 'homework', 'display': '作业多少', 'options': ['不多', '中等', '超多'] },
        {'name': 'grading', 'display': '给分好坏', 'options': ['超好', '厚道', '杀手'] },
        {'name': 'gain', 'display': '收获多少', 'options': ['很多', '一般', '没有'] },
    ]
    return render_template('new-review.html', form=form, course=course, review=review, polls=polls, message=message, is_new=is_new)
コード例 #14
0
ファイル: routes.py プロジェクト: Pandunts98/MovieFlow
def write_review(film_id):
    form = ReviewForm()
    if not form.validate_on_submit():
        return redirect(url_for('movie', film_id=film_id))
    film = Film()
    user = User()
    body = form.review.data
    user_id = user.current_user(session['__auth'])
    film.write_review(body=body, user_id=user_id, film_id=film_id)
    return redirect(url_for('movie', film_id=film_id))
コード例 #15
0
ファイル: routes.py プロジェクト: keirsjd01/microblog
def review():
    form = ReviewForm()
    if form.validate_on_submit():
        review = Reviews(name=form.name.data,
                         title=form.title.data,
                         review=form.review.data)
        db.session.add(review)
        db.session.commit()
        flash('Thank you for the post!')
    return render_template('review.html', title='Reviews.', form=form)
コード例 #16
0
def show_product_view(request, section_slug,
                      product_slug):  # показ информации и отзывы о товаре
    template = 'app/product.html'  # шаблон информации о товаре
    try:
        section = Section.objects.get(slug=section_slug)  # получение раздела
        product_data = Product.objects.prefetch_related('reviews').get(
            section=section, slug=product_slug)  # получение товаров раздела

        if request.method == 'POST':  # если метод POST
            form = ReviewForm(
                request.POST)  # берем форму отзывов у конкретного товара
            if form.is_valid(
            ):  # проверяет данные формы и возвращает True, если данные корректны
                text = form.cleaned_data[
                    'description']  # правильно обрабатывает введенные в поле данные
                rating = form.cleaned_data['mark']
                author = form.cleaned_data['name']
                new_review = Review.objects.create(
                    text=text,
                    rating=rating,
                    author=author,
                    product=product_data)  # создать новый отзыв
                ReviewProductRelation.objects.create(product=product_data,
                                                     review=new_review)
                form = ReviewForm(
                    {'name': request.user.first_name}
                )  # поле Имя в форме автоматически заполняется как имя пользователя
        else:  # если метод не POST
            form = ReviewForm(
                {'name': request.user.first_name}
            )  # поле Имя в форме автоматически заполняется как имя пользователя
        reviews = product_data.reviews.all().order_by(
            '-id')  # получить отзывы о товаре сортируя по id
        context = {
            'product_data': product_data,
            'reviews': reviews,
            'form': form
        }
    except ObjectDoesNotExist:  # если обьектов нет
        context = {}

    return render(request, template, context)
コード例 #17
0
ファイル: routes.py プロジェクト: ngaydos/bgprogresstracker
def review():
    form = ReviewForm()
    if request.method == 'POST':
        insert_rating(form.game.data, form.person.data, form.rating.data)
        flash(('Rating of {} inserted for game {} for {}').format(
            form.rating.data, form.game.data, form.person.data))
        return redirect('review')
    elif request.method == 'GET':
        return render_template('review.html',
                               title='Game Rating Update',
                               form=form)
コード例 #18
0
def post_review():
    form = ReviewForm()

    new_review = Review(comment=form.data['comment'],
                        rating=form.data['rating'],
                        spot_id=form.data['spot_id'],
                        user_id=form.data['user_id'])

    db.session.add(new_review)
    db.session.commit()
    return 'test'
コード例 #19
0
def review():
    form = ReviewForm()
    if form.validate_on_submit():
        review = Review(body=form.review.data, author=current_user)
        headline = Review(body=form.headline.data, author=current_user)
        db.session.add(review)
        db.session.add(headline)
        db.session.commit()
        flash('Your review is now live!')

    return render_template('review.html', title='Review', form=form)
コード例 #20
0
ファイル: routes.py プロジェクト: gregp31/RunOut
def new_review(foodseller_id):
    form = ReviewForm()
    if form.validate_on_submit():
        review = Review(vote=form.vote.data, text=form.text.data,
                        customer_id=current_user.id, foodseller_id=foodseller_id)
        db.session.add(review)
        db.session.commit()
        foodsellerName=review.foodseller.foodsellerName
        flash('Review created!')
        return redirect(url_for('foodseller_reviews', foodsellerName=foodsellerName))
    return render_template('create_review.html', title='New Review', form=form, legend='New Review')
コード例 #21
0
def review(request):
    review_form = ReviewForm()
    if request.method == "POST":
        review_form = ReviewForm(request.POST)
        if review_form.is_valid():
            new_review = review_form.save(commit=False)
            new_review.user_name = request.user.username
            new_review.save()
            return redirect(review)
    SaitReviews = Review.objects.all()
    assert isinstance(request, HttpRequest)
    return render(
        request, 'app/review.html', {
            'title': 'Отзыв',
            'review_form': review_form,
            'SaitReviews': SaitReviews,
            'message':
            'Если вам понравился сайт, вы можете оставить свой отзыв о проделанной мною работе',
            'year': datetime.now().year,
        })
コード例 #22
0
def create_review():
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        data = Review()
        form.populate_obj(data)
        print(str(form))
        data.assigneeId = current_user.id
        db.session.add(data)
        db.session.commit()
        return data.to_dict()
    return('Invalid Info')
コード例 #23
0
ファイル: views.py プロジェクト: sumit2312/Chronicle
def review_pending_article(request, article_id):
    reviewed_article = get_object_or_404(Article, id=article_id)
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            new_comment = form.cleaned_data['new_comment']
            if form.cleaned_data['approval'] == 'approve':
                reviewed_article.state = STAGE_ACCEPTED
            else:
                reviewed_article.state = STAGE_REJECTED
            reviewed_article.save()
            if new_comment:
                c = EditorNote(article=reviewed_article, text=new_comment)
                c.save()
            return HttpResponseRedirect(reverse('article-list'))
    else:
        form = ReviewForm()
        return render(
            request, 'editor/review-article.html', {
                'form': form,
                'article': reviewed_article,
                'comments': reviewed_article.Editornotes.all()
            })
コード例 #24
0
ファイル: biz_routes.py プロジェクト: ggard214/air_gng
def submit_review():
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        review = Review(
            rate=form.data['rate'],
            title=form.data['title'],
            comment=form.data['comment'],
            user_id=form.data['user_id'],
            service_id=form.data['service_id']
        )
    db.session.add(review)
    db.session.commit()
    return review.to_dict()
コード例 #25
0
def submitReview(business_id):
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        data = request.json
        review = Review(user_id=data['user_id'],
                        business_id=data['business_id'],
                        title=form.data['title'],
                        body=form.data['body'],
                        rating=form.data['rating'])
        db.session.add(review)
        db.session.commit()
        return review.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
コード例 #26
0
def create_review():

    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    # form populate obj
    if form.validate_on_submit():
        review = Review(product_id=request.form.get("product_id"),
                        user_id=request.form.get("user_id"),
                        content=request.form.get("content"),
                        roast_rating=request.form.get("roast_rating"))
        db.session.add(review)
        db.session.commit()

        return review.to_dict(), 201
    return {"errors": validation_errors_to_error_messages(form.errors)}, 400
コード例 #27
0
def makeReview(id):
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print("successful post")
    print("the return boy", form.data)
    if form.validate_on_submit():
        reviewData = form.data['reviews']
        ratingData = form.data['ratings']
        review = UserProduct(users_id=current_user.id,
                             products_id=int(id),
                             reviews=reviewData,
                             ratings=ratingData)
        db.session.add(review)
        db.session.commit()
        return UserProduct.to_dict_product(review)
    return "Bad Data"
コード例 #28
0
def new_review(id):
    form = ReviewForm()
    movie = get_movie(id)

    if form.validate_on_submit():
        title = form.title.data
        review = form.review.data
        new_review = Review(movie.id, title, movie.poster, review)
        new_review.save_review()
        return redirect(url_for('movie', id=movie.id))

    title = f'{movie.title} review'
    return render_template('new_review.html',
                           title=title,
                           review_form=form,
                           movie=movie)
コード例 #29
0
ファイル: routes.py プロジェクト: WyrickM/E-commerce-Website
def review_item(item_id):
    item = Item.query.get(item_id)
    buyer = User.query.get(current_user.id)
    form = ReviewForm()
    if form.validate_on_submit():
        review = Review(title = form.title.data, body = form.body.data, rating = form.rating.data)
        db.session.add(review)
        db.session.commit()
        review.add_review(buyer, item)
        total = 0
        for i in item.reviews:
            total += i.rating
        item.rating = (total / item.reviews.count())
        db.session.commit()
        flash('Your review has been recorded.')
        return redirect('/clear_search')
    return render_template('review.html', title='Review Item', form=form)
コード例 #30
0
ファイル: routes.py プロジェクト: jamco88/myflix
def review(ID):
    form = ReviewForm()
    if form.validate_on_submit():
        review = Ratings(User_id=current_user.id,
                         Score_given=form.score.data,
                         Film_id=ID)
        db.session.add(review)
        db.session.commit()
        f = open('ratings.csv', 'w')
        out = csv.writer(f)
        out.writerow(['User_id', 'Film_id', 'Score_given'])
        for item in Ratings.query.all():
            out.writerow([item.User_id, item.Film_id, item.Score_given])
        f.close()
        flash('Review DB updated - Thanks for your review!')
        return redirect(url_for('index'))
    return render_template('review.html', title='Review Page', form=form)