def review_edit_page(review_id): searchform = SearchForm() db = current_app.config["db"] review = db.get_review(review_id) if review is None: abort(404) if not current_user.id == review.author: abort(401) form = ReviewForm() if form.validate_on_submit(): score = form.data["score"] comment = form.data["comment"] author = review.author book_id = review.book review_id = review.id review_ = Review(score=score, comment=comment, author=author, book=book_id, id=review_id) db.update_review(review_) flash("Review updated successfully.") return redirect(url_for("book_page", book_id=book_id)) form.score.data = str(review.score) form.comment.data = review.comment return render_template("review_edit.html", form=form, searchform=searchform)
def edit_review(review_id): if 'student_id' in session: id = session['student_id'] review = Reviews.query.get(review_id) if review.author.username != Student.query.filter_by( student_id=id).first().username: abort(403) form = ReviewForm() if form.validate_on_submit(): if form.post.data: review.title = form.title.data review.message = form.message.data db.session.commit() flash('Review updated!', 'success') return redirect(url_for('home')) elif form.delete.data: db.session.delete(review) db.session.commit() flash('Review deleted!', 'danger') return redirect(url_for('home')) else: form.message.data = review.message form.title.data = review.title return render_template('review.html', form=form, program=review.author.program) flash('You must be logged first!', 'danger') return redirect(url_for('home'))
def review(): form = ReviewForm() conversation_id = request.form.get('conversation_id') if request.method == 'POST' and form.validate_on_submit(): rating = request.form.get('rate') rq = Request.query. \ filter(Request.id == form.request_id.data).first() # reviewed_user_id = rq.user_id if rq.user_id == current_user.id \ # else rq.from_user_id reviewed_user_id = rq.from_user_id new_review = Review( user_id=current_user.id, reviewed_user_id=reviewed_user_id, request_id=rq.id, comment=form.comment.data, rating=rating ) db.session.add(new_review) db.session.commit() flash(u"Yorumunuz eklendi :)") return redirect('/show_stuff/%s' % rq.stuff_id) flash(u"Mesaj alanını boş bıraktınız.") return redirect('/conversation/%s' % conversation_id)
def edit_review(review_id): """Returns and processess form to edit a review""" if not g.user: flash("Access unauthorized.", "danger") return redirect("/") review=Review.query.get(review_id) form=ReviewForm(obj=review) drink_name=review.drink.name if form.image.data: display_img=form.image.data else: display_img="https://banner2.cleanpng.com/20190714/uvh/kisspng-martini-cocktail-glass-clip-art-vector-graphics-home-forty-two-peterborough-5d2b093a9f6130.8579484215631014986528.jpg" if form.validate_on_submit(): review.rating=round(float(form.rating.data),2) review.review=form.review.data review.image=display_img db.session.commit() flash("Your changes have been saved", 'success') return redirect("/") return render_template("edit_review.html", form=form, drink=drink_name)
def book_page(book_id): searchform = SearchForm() db = current_app.config["db"] book, author_id = db.get_book(book_id) reviews, users = db.get_reviews(book_id) if book is None: abort(404) form = ReviewForm() if form.validate_on_submit(): score = form.data["score"] comment = form.data["comment"] author = db.get_user_id(current_user.username) review = Review(author=author, book=book_id, score=score, comment=comment) review_id = db.add_review(review) review.id = review_id return redirect(url_for("book_page", book_id=book_id)) return render_template("book.html", book=book, author_id=author_id, form=form, reviews=reviews, users=users, searchform=searchform)
def barbers(id=None): if request.args.get('neighborhood') == 'choose': neighborhood_code = "ga" else: neighborhood_code = request.args.get('neighborhood') neighborhood = neighborhoods_by_key.get(neighborhood_code) form = forms.PostForm() if id == None: barbers = models.Barber.select().limit(100) return render_template('barbers.html', barbers=barbers, form=form, neighborhood=neighborhood) else: barber_param = int(id) barber = models.Barber.get(models.Barber.id == barber_param) reviews = barber.reviews form = ReviewForm() if form.validate_on_submit(): models.Review.create(barber=barber_param, user_id=g.user._get_current_object(), text=form.text.data.strip(), rating=form.rating.data.strip()) flash("You created a review") return render_template("barber.html", barber=barber, reviews=reviews, form=form, pub_key=pub_key)
def review_for(saved_drink_id): """Returns and processes form to make a review for a drink""" if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = ReviewForm() saved_drink=Saved_recipe.query.get(saved_drink_id) if form.validate_on_submit(): if form.image.data: display_img=form.image.data else: display_img="https://banner2.cleanpng.com/20190714/uvh/kisspng-martini-cocktail-glass-clip-art-vector-graphics-home-forty-two-peterborough-5d2b093a9f6130.8579484215631014986528.jpg" review = Review( drink_id= saved_drink.drink.id, rating=round(float(form.rating.data),2), review=form.review.data, image=display_img, user_id=g.user.id ) db.session.add(review) db.session.commit() return redirect("/") return render_template("single_review.html", saved_drink=saved_drink, form=form)
def add_review(): """ Add review functionality """ form = ReviewForm() if form.validate_on_submit(): # Assign all parts of the form to variables and add review to mongoDB review = { "material_name": form.material_name.data, "brand": form.brand.data, "filament_name": form.filament_name.data, "author": session["user"], "rating": int(form.rating.data), "temperature": form.temp.data, "finish": form.finish.data, "colour": form.colour.data, "review_text": form.review.data, "image_url": form.image.data, "cost": int(form.cost.data), "likes": 0 } mongo.db.reviews.insert_one(review) flash("Thanks for your review!") return redirect(url_for("add_review")) return render_template("add_review.html", form=form)
def handle_review_page(beer_id): """Page with form to fill out review of beer and submit""" if CURR_USER_KEY in session: form = ReviewForm() response = requests.get(f"{API_BASE_URL}/beers", params={ 'key': API_KEY, 'ids': beer_id }) beer = response.json()["data"][0] user_id = session[CURR_USER_KEY] if form.validate_on_submit(): new_review = Review(beer_name=beer["name"], user_id=user_id, beer_id=beer_id, rating=form.rating.data, text=form.text.data) db.session.add(new_review) db.session.commit() flash("Review submitted!", "success") return redirect(f"/user/{user_id}/reviews") else: return render_template("beer/review.html", form=form, beer=beer) else: flash("Please Log-In First", "danger") return redirect("/")
def book(bid): # Information about the book book = db.get_book(bid) uid = db.get_uid(session['user']) # Book rating and reviews avg_rating = db.get_avg_rating(bid) reviews = db.get_reviews(bid) # Book rating on GoodReads gr_rating = goodreads_rating(book['isbn']) form = ReviewForm() if form.validate_on_submit(): # Checks whether the user has reviewed this book review_counter = db.get_review(bid, uid) if review_counter == 0: review = form.review.data rating = int(form.rating.data) db.add_review(uid, bid, review, rating) else: flash("You have already left a review") return redirect(url_for('book', bid=bid)) return render_template('book.html', title=book['title'], book=book, form=form, reviews=reviews, rating=avg_rating, gr_rating=gr_rating)
def show(id): form = ReviewForm() if "username" in session: if request.method == "POST": if form.validate_on_submit(): controller.add_review(id, form.reviews.data, form.rating.data) book = controller.get_book_by_id(id) if book: res = requests.get( "https://www.goodreads.com/book/review_counts.json", params={ "key": f"{KEY}", "isbns": f"{book.isbn}" }) ratings = res.json()["books"][0] return render_template('pages/book.html', book=book, ratings=ratings, form=form, reviews={ "all_reviews": controller.get_reviews_by_id(book.id), "current_user_submitted": controller.is_review_submitted(book.id) }) return render_template('pages/book.html') return redirect(url_for("login"))
def edit_review(id): ''' Function to display a page which displays a form to edit a review for logged in user ''' if 'logged' not in session: # if a user trys to go to edit review without been logged in flash('You need to log in to edit a review', 'warning') return redirect(url_for('login')) # sending to log in one_review = mongo.db.reviews.find_one({'_id': ObjectId(id)}) # retrieving record from db # if a user trys to go to edit review that they don't own if one_review['username'] != session['username']: flash('You do not own this review and cannot edit it. ', 'warning') return redirect(url_for('login')) # sending to log in form = ReviewForm(data=one_review) if form.validate_on_submit(): # if form submits successfully reviews = mongo.db.reviews # creating amazon link amazon_link = create_amazon_search(request.form['book_title']) icon = get_icon_class(request.form['category']) # creating icon font awesome class # add form content to db as a new record reviews.update_one({'_id': ObjectId(id)}, { '$set': { 'author': request.form['author'], 'book_title': request.form['book_title'], 'summary': request.form['summary'], 'review': request.form['review'], 'category': request.form['category'], 'amazon': amazon_link, 'icon': icon, } }) flash('Review Updated ', 'success') # send to my review template on successful addupdate return redirect(url_for('review', id=id)) return render_template('editreview.html', form=form, title='Edit a Review')
def add_review(book_id): """ Function to load WTForm for adding review on book WTForms code adapted from Corey Shafer's tutorial found at https://www.youtube.com/watch?v=UIJKdCIEXUQ&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=3 """ # Check if user logged in if g.user: form = ReviewForm() # Validation of form and insert in collection if form.validate_on_submit(): flash(f"New review uploaded!", "success") review = { "review": form.review.data, "book_id": book_id, "user_id": g.user, "date_added": date.today().strftime("%Y/%m/%d"), "csrf_token": form.csrf_token.data } reviews = mongo.db.reviews reviews.insert_one(review) return redirect( url_for( "get_book", book_id=book_id, _scheme="https", _external=True)) # Check to see type of user and return of form for correction else: super_user = mongo.db.users.find_one({"username": "******"}) if g.user == str(super_user["_id"]): return render_template( "addreview.html", form=form, book_id=book_id, super_user=g.user) else: return render_template( "addreview.html", form=form, book_id=book_id, regular_user=g.user) else: flash(f"You need to log in first...", "warning") return redirect( url_for( "log_user_in", _scheme="https", _external=True))
def create_review(): form = ReviewForm() if form.validate_on_submit() and 0 < form.rating.data < 6: models.Review.create(user=g.user._get_current_object(), plant=form.plant.data, rating=form.rating.data, text=form.text.data) return redirect(url_for('stream')) else: flash( "Could not submit review, please ensure you have filled out all the fields correctly" ) return redirect(url_for('stream'))
def add_review(): ''' Function to display a page which displays a form to add a review for logged in user ''' if 'logged' not in session: # if a user trys to go to add review without been logged in flash('You need to log in to add a review', 'warning') return redirect(url_for('login')) # sending to log in form = ReviewForm() if form.validate_on_submit(): # if form submits successfully reviews = mongo.db.reviews # creating amazon link amazon_link = create_amazon_search(request.form['book_title']) icon = get_icon_class(request.form['category']) # creating icon font awesome class # add form content to db as a new record reviews.insert_one({ 'author': request.form['author'], 'book_title': request.form['book_title'], 'summary': request.form['summary'], 'review': request.form['review'], 'category': request.form['category'], 'amazon': amazon_link, 'icon': icon, 'upvote': 0, 'username': session['username'], }) flash('Review added ', 'success') # send to my reviews template on successful add return redirect(url_for('my_reviews')) return render_template('addreview.html', form=form, title='Add Review')
def edit_review(review_id): """if user is logged in and owns review, edit a review""" if CURR_USER_KEY in session: edit_review = Review.query.get(review_id) if session[CURR_USER_KEY] == edit_review.author.id: form = ReviewForm(obj=edit_review) beer_id = edit_review.beer_id response = requests.get(f"{API_BASE_URL}/beers", params={ 'key': API_KEY, 'ids': beer_id }) beer = response.json()["data"][0] user_id = session[CURR_USER_KEY] if form.validate_on_submit(): edit_review.rating = form.rating.data edit_review.text = form.text.data db.session.add(edit_review) db.session.commit() flash("Review Updated", "success") return redirect(f"/user/{user_id}/reviews") else: return render_template("beer/editreview.html", form=form, beer=beer) else: flash("Only author can edit or delete posts!", "warning") return redirect("/") else: flash("Must be logged-in", "danger") return redirect("/")
def add_review(): form = ReviewForm() if form.validate_on_submit(): reviews = mongo.db.reviews # ADD A RECORD reviews.insert_one({ 'author': request.form['author'], 'title': request.form['title'], 'summary': request.form['summary'], 'review': request.form['review'], 'image': request.form['image'], 'ratings': request.form['ratings'], 'username': session['username'], }) flash('You have a reviewed a book', 'success') # SENDS TO REVIEWS UPON SUCCESS return redirect(url_for('my_reviews')) return render_template('add_review.html', title='Add Review', form=form)
def edit_review(id): # GETTING THE USERS REVIEW db_review = mongo.db.reviews.find_one({'_id': ObjectId(id)}) form = ReviewForm(data=db_review) if form.validate_on_submit(): reviews = mongo.db.reviews # THE DOCUMENT MODEL reviews.update_one({'_id': ObjectId(id)}, { '$set': { 'author': request.form['author'], 'title': request.form['title'], 'summary': request.form['summary'], 'review': request.form['review'], 'image': request.form['image'], 'ratings': request.form['ratings'] } }) flash('Updated', 'success') return render_template('edit_review.html', form=form, title='Edit Review')
def review(book_id): form = ReviewForm() username = session.get('username') user = db.execute("SELECT * FROM users WHERE username = :username", { "username": str(username) }).fetchone() book = db.execute("SELECT * FROM books WHERE id = :id", { "id": int(book_id) }).fetchone() user_id = int(user.id) book_id = int(book.id) if db.execute( "SELECT * FROM posts WHERE user_id = :user_id and book_id = :book_id", { "user_id": user_id, "book_id": book_id, }).rowcount != 0: flash('Sorry... You can make just one review for each book', 'danger') return redirect(url_for('yourpost', book_id=book.id)) if form.validate_on_submit(): db.execute( "INSERT INTO posts (header, content, rating, book_id, user_id) VALUES (:header, :content, :rating, :book_id, :user_id)", { "header": form.header.data, "content": form.content.data, "rating": int(form.rating.data), "user_id": int(user.id), "book_id": int(book.id) }) db.commit() flash('Posted with sucess', 'success') book_id = book.id return redirect(url_for('book', book_id=book.id)) return render_template('review.html', book=book, pagetitle=book.title, navbar='x', form=form, username=username, user=user, user_id=user_id, book_id=book.id)
def review(): if 'student_id' in session: form = ReviewForm() del form.delete id = session['student_id'] if form.validate_on_submit(): if form.post.data: review = Reviews(student_id=id, title=form.title.data, message=form.message.data) db.session.add(review) db.session.commit() flash('Thanks for your review!', 'success') return redirect(url_for('home')) else: return render_template('review.html', form=form, program=Student.query.get(id).program) flash('You must be logged first!', 'danger') return redirect(url_for('home'))
def review(affiliate_id=None): form = ReviewForm() a = models.Affiliate.query.get(affiliate_id) if form.validate_on_submit(): try: r = models.Review(affiliate_id=a.id, ipaddress=request.remote_addr, rating_overall=form.rating.data, rating_equipment=form.rating_equipment.data, rating_instructor=form.rating_instructor.data, comment=form.comment.data, review_date=datetime.datetime.utcnow()) db.session.add(r) db.session.commit() flash("Review for %s has been posted!" % a.name, 'success') return redirect('/') except: db.session.rollback() flash('You only can post one review!', 'error') else: if request.method == "POST": flash('Please make sure all fields are filled out correctly.', 'error') return render_template('review.html', affiliate_info = a, form = form)
def add_feedback(username): if "user_id" not in session: return redirect("/login") else: form = ReviewForm() if form.validate_on_submit(): title = form.title.data content = form.content.data review = Review(title=title, content=content, user_id=session["user_id"]) db.session.add(review) db.session.commit() return redirect(f"/feedback/{review.id}") else: return render_template("feedback-form.html", form=form)
def add(week_id): """Add a daily review task.""" f = ReviewForm() # print(f.data) if f.validate_on_submit(): review_dt = datetime.combine(f.date.data, time.min) rev = Review.query.filter_by(review_day=review_dt).first() if rev is None: rev = Review() rev.week_id = week_id rev.review_day = f.date.data db.session.add(rev) db.session.commit() rev.planning = f.planning.data if f.planning.data else rev.planning rev.dev = f.dev.data if f.dev.data else rev.dev rev.tickets = f.tickets.data if f.tickets.data else rev.tickets rev.cleanup = f.cleanup.data if f.cleanup.data else rev.cleanup rev.review = f.review.data if f.review.data else rev.review rev.goals = f.goals.data if f.goals.data else rev.goals db.session.commit() # else: # print('validation failed') return redirect(url_for('worksheet.worksheet', week_id=week_id))
def update_feedback(review_id): if "user_id" not in session: return redirect("/login") else: review = Review.query.get_or_404(review_id) if review.user_id == session["user_id"]: form = ReviewForm(obj=review) if form.validate_on_submit(): review.title = form.title.data review.content = form.content.data db.session.commit() return redirect(f"/feedback/{review.id}") else: return render_template("feedback-form.html", form=form) return redirect("/")
def index(): form = ReviewForm() print(request.method) if request.method == 'POST': if form.validate_on_submit(): form_data_list = [form.username.data, form.product_name.data, form.product_review.data] print(f'User name {form.username.data}') print(f'Product Name {form.product_name.data}') print(f'Product Review {form.product_review.data}') with open('static/data/reviews.csv', 'a+', newline='') as write_obj: csv_writer = csv.writer(write_obj) csv_writer.writerow(form_data_list) form.username.data = '' form.product_name.data = '' form.product_review.data = '' print(f'submitted successfully') print('hi') # flash('Review Posted Successfully!', category='info') return redirect('/') with open('static/data/reviews.csv') as csv_file: data = csv.reader(csv_file, delimiter=',') first_line = True reviews = [] for row in data: if first_line: first_line = False else: reviews.append(dict(username=row[0], product_name=row[1], product_review=row[2])) return render_template('index.html', form=form, reviews=reviews)
def create_movie_review(movie_id): """Show a form for a user to create a review for a movie, and add the review to reviews table.""" if not g.user: flash("You must be signed in to leave a review") return redirect("/") movie = get_results(requests.get(f"{api_base}movie/{movie_id}{api_key}")) if is_movie(movie) == False: flash("We couldn't find that movie.") return redirect("/") in_movies(movie) form = ReviewForm() if form.validate_on_submit(): review = Review(title=form.title.data, body=form.body.data, rating=form.rating.data, username=g.user.username, movie_id=movie_id) db.session.add(review) db.session.commit() return redirect(f"/movie/{movie_id}") return render_template("movies/review.html", movie=movie, form=form)
def edit_review(book_id): """ Function to load form for a review to be changed and render to html. Checks first whether a user is logged in and whether user is same as original reviewer before performing function. """ # Check if user logged in if g.user: the_review = mongo.db.reviews.find_one({"book_id": book_id}) # Check if user same as reviewer if g.user == the_review["user_id"]: form = ReviewForm() if form.validate_on_submit(): flash(f"Review successfully edited!", "success") reviews = mongo.db.reviews reviews.update({"_id": ObjectId(the_review["_id"])}, { "review": form.review.data, "book_id": book_id, "user_id": g.user, "date_added": date.today().strftime("%Y/%m/%d"), "csrf_token": form.csrf_token.data }) return redirect( url_for( "get_book", book_id=book_id, _scheme="https", _external=True)) # Check user type and render relevant options else: super_user = mongo.db.users.find_one({"username": "******"}) if g.user == str(super_user["_id"]): return render_template( "editreview.html", book_id=book_id, review=the_review, form=form, super_user=g.user) else: return render_template( "editreview.html", book_id=book_id, review=the_review, form=form, regular_user=g.user) else: flash( f"You cannot edit this review, as it was uploaded by someone else...", "danger") return redirect( url_for( "get_book", book_id=book_id, _scheme="https", _external=True)) else: flash(f"You need to log in first...", "warning") return redirect( url_for( "log_user_in", _scheme="https", _external=True))
def movie(imdb_id): #Uses Review Form object from forms.py form = ReviewForm() #Update DB when new form is submitted if form.validate_on_submit(): db.execute( "INSERT INTO reviews (userid, imdbid, rating, content) VALUES (:un, :ii, :ra, :co);", { "un": session['current_user'], "ii": imdb_id, "ra": form.select.data, "co": form.content.data }) db.commit() return (redirect(url_for('movie', imdb_id=imdb_id))) # Ensure that movie exists movie = db.execute("SELECT * FROM movies WHERE imdbid = :id", { 'id': imdb_id }).fetchone() if movie == None: abort(404) else: #Retrieve additional data from omdb imdb_id = movie[3] attrlist = [ "Title", "Year", "Rated", "Released", "Runtime", "Genre", "Director", "Writer", "Actors", "Plot", "Language", "Country", "Awards", "Poster", "Metascore", "imdbRating", "imdbVotes", "imdbID", "Type", "DVD", "BoxOffice", "Production", "Website", "Response" ] omdbResults = omdb.request(i=imdb_id) omdbData = omdbResults.json() temp = {} for attr in attrlist: temp[attr] = omdbData[attr] # Get all reviews revu = db.execute("SELECT * FROM reviews WHERE imdbid = :imdbid", { "imdbid": imdb_id }).fetchall() attrlist2 = ["Author", "MovieID", "Rating", "ReviewContent"] reviews = [] temp2 = {} #Check if user has submitted a review userRev = False for i in range(len(revu)): temp2 = {} for j in range(len(revu[i])): temp2[attrlist2[j]] = revu[i][j] reviews.append(temp2) if temp2['Author'] == session['current_user']: userRev = True #Sets reviews to blank list, not None if revu == None: reviews = [] #Get average score from Metascore & imdbRating try: avgR = (float(temp['Metascore']) + float(temp['imdbRating']) * 10) / 2 except: try: avgR = temp['imdbRating'] except: avgR = temp['Metascore'] return render_template("movie.html", movie=temp, reviews=reviews, avgR=avgR, form=form, userRev=userRev)
def sub(): form = ReviewForm() if form.validate_on_submit(): flash('Review Submitted Successfully') return render_template('home.html', form=form)
def bookdetail(book_id): form = ReviewForm() query_isbn = f"%{book_id}%".lower() # select book from database book_res = db.execute("SELECT * FROM books WHERE isbn LIKE :isbn LIMIT 1", { "isbn": query_isbn }).fetchone() # check if user has existing review in database user_existing_review = db.execute( "SELECT * FROM reviews WHERE isbn = :isbn AND user_name = :user_name", { "isbn": query_isbn, "user_name": session["user_name"] }).fetchone() # request Goodreads data goodreads_request = requests.get( "https://www.goodreads.com/book/review_counts.json", params={ "key": "6vsh1pJmzHPFQE7G6jppw", "isbns": book_id }) # select other user reviews from database other_user_reviews = db.execute( "SELECT * FROM reviews WHERE isbn = :isbn EXCEPT SELECT * FROM reviews WHERE user_name = :user_name", { "isbn": query_isbn, "user_name": session["user_name"] }).fetchall() info = goodreads_request.json() goodreads_rating = float(info['books'][0]['average_rating']) goodreads_rating_num = int(info['books'][0]['ratings_count']) if user_existing_review: # if the user has an existing review, display that review return render_template('bookdetail.html', book=book_res, review=user_existing_review, goodreads_rating=goodreads_rating, rating_num=goodreads_rating_num, other_users=other_user_reviews) if form.validate_on_submit(): # submit review and rating to the database rating = form.rating.data review = form.review.data db.execute( "INSERT INTO reviews (user_name, rating, review, isbn) VALUES (:user_name, :rating, :review, :isbn)", { "user_name": session["user_name"], "rating": rating, "review": review, "isbn": query_isbn }) db.commit() flash(f"Your review has been submitted!", 'success') return render_template('bookdetail.html', book=book_res, form=form, goodreads_rating=goodreads_rating, rating_num=goodreads_rating_num, other_users=other_user_reviews)
def book(book_isbn): form = ReviewForm() # call application own API to get book details r_api = requests.get(f'{api_host}{book_isbn}') if r_api.status_code != 200: return abort(404) try: book_json = r_api.json() except JSONDecodeError: return abort(500) # call goodreads API to get book details try: r_gr_api = requests.get( "https://www.goodreads.com/book/review_counts.json", params={"key": gr_api_key, "isbns": book_isbn}) except requests.RequestException: r_gr_api = None try: gr_api_json = r_gr_api.json() except JSONDecodeError: gr_api_json = None # check for book id book_id = db.execute( 'SELECT id FROM public.book ' 'WHERE isbn = :isbn', {'isbn': book_json['isbn']} ).fetchone() # insert or update review if form submitted if request.method == 'POST' and form.validate_on_submit(): db.execute( 'INSERT INTO public.user_book (user_id, book_id, score, review) ' 'VALUES (:user_id, :book_id, :score, :review) ' 'ON CONFLICT (user_id, book_id) ' 'DO UPDATE SET score = :score, review = :review', {"user_id": session['user_id'], "book_id": book_id[0], "score": form.rating.data, "review": form.review.data }) db.commit() return redirect(url_for('book', book_isbn=book_isbn)) # get reviews (newest first) r_q = db.execute( 'SELECT public.user_book.*, ' 'public.user.name ' 'FROM public.user_book ' 'JOIN public.user ' 'ON public.user.id = public.user_book.user_id ' 'WHERE book_id = :book_id ' 'ORDER BY (id) DESC ', {"book_id": book_id[0]} ).fetchall() # build list of reviews and check if current user already send a review reviews = [] already_review = False for r_api in r_q: if r_api[5] == session['user']: already_review = True form.review.default = r_api[4] form.rating.default = int(r_api[3]) form.process() reviews.append( {'user': r_api[5], 'rating': r_api[3], 'review': r_api[4]}) return render_template( 'book.html', form=form, book_json=book_json, gr_api_json=gr_api_json, reviews=reviews, already_review=already_review )