def add_rating(request, profID): if request.method == 'POST': form = RatingForm(request.POST) if form.is_valid(): rating = Rating() rating.professor = Professor.objects.get(id=profID) rating.poster = request.user rating.overall = form.cleaned_data['overall'] rating.humor = form.cleaned_data['humor'] rating.difficulty = form.cleaned_data['difficulty'] rating.availability = form.cleaned_data['availability'] if Rating.objects.filter(poster=request.user).filter(professor=rating.professor).count > 0: params = { 'message': 'You cannot rate a professor multiple times', } return render(request, 'message.html', params) rating.save() return HttpResponseRedirect('/accounts/profs/profID/' + profID + '/') else: form = RatingForm() prof = Professor.objects.get(id=profID) params = { 'form': form, 'formTitle': 'Add a rating for ' + str(prof.firstName) + ' ' + str(prof.lastName), } return render(request, 'profSearch.html', params)
def api_add_rating(request, course_id): if request.method == 'POST': form = RatingForm(request.POST) results = [] if form.is_valid(): rating = form.save(commit=False) rating.user = UserProfile.objects.get(user=int(request.user.id)) rating.date = datetime.datetime.now() try: c = Course.objects.get(id=int(course_id)) rating.course = c rating.save() #update the course averages c.number_of_ratings += 1 c.average_difficulty = ((c.average_difficulty if c.average_difficulty else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['difficulty_rating'])) \ / Decimal(c.number_of_ratings) c.average_teaching = ((c.average_teaching if c.average_teaching else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['teaching_rating'])) \ / Decimal(c.number_of_ratings) c.average_materials = ((c.average_materials if c.average_materials else 0) * (c.number_of_ratings - 1) + Decimal(form.cleaned_data['materials_rating'])) / Decimal(c.number_of_ratings) c.average_overall = ((c.average_overall if c.average_overall else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['overall_rating'])) \ / Decimal(c.number_of_ratings) c.average_satisfaction = ((c.average_satisfaction if c.average_satisfaction else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['satisfaction_rating'])) \ / Decimal(c.number_of_ratings) c.save() #response contains averages for the course, and the username of the submitter msg = {"data": { "overall": float(c.average_overall), "satisfaction": float(c.average_satisfaction), "difficulty": float(c.average_difficulty), "teaching": float(c.average_teaching), "materials": float(c.average_materials), "ratings": c.number_of_ratings, "username": request.user.username } } results.append(msg) except Exception as e: return HttpResponseRedirect('/') else: print form.errors errors = {"errors": form.errors } results.append(errors) return HttpResponse(json.dumps(results), content_type="application/json") else: return course(request, course_id)
def edit_rating(): conn = mysql.connector.connect(**config) c = conn.cursor(buffered=True) if request.method == "GET": form = RatingForm() c.execute("SELECT * FROM Rating") rating = c.fetchall() return render_template('edit_rating.html', title='edit_rating', rating=rating, form=form) elif request.method == 'POST': form = RatingForm(request.form) uid = request.form.get("uid") rid = request.form.get('rid') #comment = request.form.get('comment') stars = request.form.get('stars') c.execute("SELECT * FROM Rating R WHERE R.rid=" + (rid)) #results = c.fetchall() query = "UPDATE Rating SET Stars = " + str(stars) + ", Uid = " + str( uid) + " WHERE rid= " + str(rid) c.execute(query) conn.commit() flash(f'Rating has been edited!.', 'success') return redirect(url_for('rating'))
def rate(id_val): form = RatingForm(request.form) if request.method == 'POST' and form.validate(): movieId = id_val audienceId = current_user.get_id() rating = form.rating.data add_rating(db, movieId, audienceId, rating) flash('Rating successfully entered.') return redirect(url_for('show_movie_info',id_val= id_val)) return render_template('Rating_page.html', form=form)
def test_form_fails_with_invalid_data(self): """Test that form will fail if given invalid data.""" form_data = { 'score': 11, 'beer_name': "Test Beer", 'brewer_name': "Test Co", 'notes': "Test Notes" } form = RatingForm(data=form_data) self.assertFalse(form.is_valid())
def process_rating(request): if request.method == "POST": form = RatingForm(request.POST) if form.is_valid(): practice_item = get_object_or_404(FlashCard, pk=int(form.cleaned_data['id'])) practice_item.set_next_practice(int(form.cleaned_data['rating'])) practice_item.save() return redirect(to='list_flashcards') else: return HttpResponseBadRequest("There's nothing here. Haha.")
def create_and_save_rating(): """Creates a new rating and saves it in the database.""" form_data = { 'score': 9, 'beer_name': "Test Beer", 'brewer_name': "Test Co", 'notes': "Test Notes" } form = RatingForm(data=form_data) rating = form.save() return rating
def identify(): form = RatingForm() if form.validate_on_submit(): rating = form.rating.data print session['user_id'], 1, rating cur = mysql.connection.cursor() cur.execute("INSERT INTO user_article VALUES(%s, %s, %s)", (session['user_id'], 1, rating)) mysql.connection.commit() cur.close() flash('Rating is submitted for this article', 'success') return redirect(url_for('identify')) return render_template('identify.html', form=form)
def test_form_data_is_valid(self): """Test that rating form is working.""" form_data = { 'score': 9, 'beer_name': "Test Beer", 'brewer_name': "Test Co", 'notes': "Test Notes" } form = RatingForm(data=form_data) self.assertTrue(form.is_valid()) rating = form.save() self.assertEqual(rating.score, 9) self.assertEqual(rating.beer_name, "Test Beer") self.assertEqual(rating.brewer_name, "Test Co") self.assertEqual(rating.notes, "Test Notes")
def edit_rating(): if request.method=="GET": form = RatingForm() conn = mysql.connector.connect(**config) conn.row_factory = dict_factory c = conn.cursor() c.execute("SELECT * FROM Rating") rating = c.fetchall() return render_template('edit_rating.html', title='edit_rating', form=form)
def demo_rate(request, demoid): context = RequestContext(request) context_dict ={} t = get_team(request.user) add_isteam_to_context_dict(context_dict, t) rater = get_rater(request.user) if rater: if request.method == 'POST': rating_form = RatingForm(data=request.POST) if rating_form.is_valid(): demo = Demo.objects.get(id=demoid) # check if the rater has already rated this app, if so, remove this entry and replace with new rating rating_check = Rating.objects.filter(rater=rater,demo=demo).count() if rating_check == 1: past_rating = Rating.objects.get(rater=rater,demo=demo) demo.rating_count = demo.rating_count - 1 demo.rating_sum = demo.rating_sum - past_rating.score past_rating.delete() demo.save() rating = rating_form.save(commit=False) rating.rater = rater rating.demo = demo rating.save() demo.rating_count = demo.rating_count + 1 demo.rating_sum = demo.rating_sum + rating.score demo.save() return HttpResponseRedirect('/showcase/demo/show/'+str(demoid)+'/') else: print rating_form.errors else: rating_form = RatingForm() context_dict['rating_form']=rating_form return render_to_response( 'showcase/demo.html', context_dict, context) return HttpResponseRedirect('/showcase/demo/show/'+str(demoid)+'/')
def rate_show(): form = RatingForm(request.form) if request.method == 'POST' and form.validate(): # Check if the rater is a buyer cnx = mysql.connector.connect(user='******', password='******', host='104.197.213.149', database='wgzzdb') cursor = cnx.cursor() checker = "SELECT BuyerSSN FROM Buyers WHERE BuyerSSN = " + str( form.data['ssn']) + ";" cursor.execute(checker) results = cursor.fetchall() if not results: flash('Not eligible to rate!') return redirect('/') # Check if the rater's name and SSN match checker = "SELECT BuyerSSN, BuyerName FROM Buyers WHERE BuyerSSN = " + str( form.data['ssn'] ) + " AND BuyerName = " + "'" + form.data['name'] + "';" cursor.execute(checker) results = cursor.fetchall() if not results: flash('Name and SSN did not match!') return redirect('/') # Add a piece of rating info date = datetime.today() rating = dict(RatingForm.rate).get(form.rate_choice.data) query = "INSERT INTO Rating (BuyerSSN, ShowName, Rating, RatingDate) VALUES (%s, %s, %s, %s)" val = (form.data['ssn'], form.data['show'], int(rating), date) cursor.execute(query, val) cnx.commit() cursor.close() cnx.close() flash('Rate successful!') return redirect('/') return render_template('rate_show.html', form=form)
def home(): form = RatingForm() # def clean_text(text): # text = text.lower() # clean = re.compile('<.*?>') # text = re.sub(clean,'',text) # text = re.sub(r"""[,.;@#?!&$]+\ *"""," ",text, flags=re.VERBOSE) # text = text.replace('\r\n', '-').replace('\n', ' ') # check = text.replace(" ", "").isalpha() # if check: # text = [word for word in word_tokenize(text)] # else: # text = [word for word in word_tokenize(text) if word.isalpha()] # return text # def stem(text): # text = ' '.join([porter.stem(word) for word in text.split()]) # return text if form.validate_on_submit(): review = form.review.data #review = clean_text(review) review = review.lower() clean = re.compile('<.*?>') review = re.sub(clean,'',review) review = re.sub(r"""[,.;@#?!&$]+\ *"""," ",review, flags=re.VERBOSE) review = review.replace('\r\n', '-').replace('\n', ' ') review = [word for word in review.split() if word.isalpha()] STOPWORDS= set(["a","about","above","after","again","against","am","an","and","any","are","as","at","be","been","before","being","below","between","both","by","can","could","did","do","does","doing","down","during","each","few","for","from","further","had","has","have","having","he","he'd","he'll","he's","her","here","here's","hers","herself","him","himself","his","how","how's","i","i'd","i'll","i'm","i've","in","into","is","isn't","it","it's","its","itself","let's","me","more","myself","of","off","on","once","only","or","other","ought","our","ours" ,"ourselves","out","over","own","same","she","she'd","she'll","she's","should","so","some","such","than","that","that's","the","their","theirs","them","hemselves","then","there","there's","these","they","they'd","they'll","they're","they've","this","those","through","to","too","under","until","up","very","was","we","we'd","we'll","we're","we've","were","what","what's","when","when's","where","where's","which","while","who","who's","whom","why","why's","with","would","you","you'd","you'll","you're","you've","your","yours","yourself","yourselves","return","hes","heres","hows","im","its","lets","shes","thats","theres","theyll","theyre","theyve","were","whats","whens","wheres","whos","whys","youd","youll","youre","youve"]) STOPWORDS_dict = dict.fromkeys(STOPWORDS, 0) review = [word for word in review if word not in STOPWORDS_dict] review = ' '.join(word for word in review) # porter=PorterStemmer() # review = ' '.join([porter.stem(word) for word in review.split()]) vocab = open('models/Vocab.pickle', 'rb') vocab_pickled = pickle.load(vocab) vectorizer = TfidfVectorizer(vocabulary=vocab_pickled.vocabulary_) model = open('models/LinearRegression.pickle', 'rb') linearregression_pickled = pickle.load(model) p = vectorizer.fit_transform([review]) rate = round(linearregression_pickled.predict(p)[0],2) flash(f'YOUR REVIEW : {review}','success') flash(f'MY MODEL RATING : { rate }','success') return redirect(url_for('predict')) return render_template('PredictReviewRating.html',form=form)
def movie_rating(id): form = RatingForm() movie = mg.db.movie.find_one({'_id': id}) form.uid.data = current_user.uid form.mid.data = movie['lens_id'] form.name.data = movie['title'] if form.validate_on_submit() and request.method == 'POST': Rating(uid=int(form.uid.data), mid=int(form.mid.data), name=form.name.data, rating=float(form.rating.data), title=form.title.data, content=form.content.data).save() recommender.add_ratings( [[int(form.uid.data), int(form.mid.data), float(form.rating.data)]]) flash('rating recorded, retraining model...') return redirect(url_for('main.movie_rating', id=id)) return render_template('rating.html', movie=movie, form=form)
def test_edit_rating(self): """Test that edit rating feature is working by checking database values before and after edit of beer name.""" rating = create_and_save_rating() rating_in_db = Rating.objects.filter(pk=rating.pk).exists() self.assertEqual(rating.beer_name, "Test Beer") response = self.client.post(reverse('rating_edit', args=(rating.pk, ))) form_data = { 'score': 9, 'beer_name': "Testing Edit", 'brewer_name': "Test Co", 'notes': "Test Notes" } form = RatingForm(data=form_data) self.assertTrue(form.is_valid()) rating = form.save() self.assertEqual(rating_in_db, True) self.assertEqual(rating.beer_name, "Testing Edit") self.assertEqual(response.status_code, 200)
def course(request, course_id): context = RequestContext(request) form = RatingForm(request.GET) if request.user.is_authenticated(): submitted = Rating.objects.filter( course=Course.objects.get(id=int(course_id)), user=UserProfile.objects.get(user=int(request.user.id))).exists() else: submitted = False try: c = Course.objects.get(id=int(course_id)) c.hit() c.save() ratings = Rating.objects.all().filter(course=int(course_id)) except: #course doesnt exist? Back to homepage then return HttpResponseRedirect('/') return render_to_response('course.html', locals(), context)
def home(request): # scrape_imdb() u = request.user rated_items = UserRating.objects.filter(corresponding_user=u) movies = Movie.objects.all() name_to_path_dicts = [] name_to_path = {} name_to_url = {} name_to_form = {} name_to_id = {} count = 1 blacklisted_movies = [] for rated_item in rated_items: if rated_item.movie in movies: blacklisted_movies.append(rated_item.movie) for movie in movies: if movie not in blacklisted_movies: rating_form = RatingForm(request.POST or None) name_to_form[movie.name] = rating_form name_to_path[movie.name] = movie.image name_to_url[movie.name] = movie.url name_to_id[movie.name] = movie.movielens_id if count % 4 == 0: name_to_path_dicts.append(name_to_path) name_to_path = {} count += 1 name_to_path_dicts.append(name_to_path) if len(rated_items) < 10: heading = "Please rate atleast %d more item(s)" % (10 - len(rated_items)) button_status = 'disabled' else: heading = "You may proceed" button_status = '' context = { 'heading': heading, 'name_to_path_dicts': name_to_path_dicts, 'name_to_url': name_to_url, 'name_to_form': name_to_form, 'name_to_id': name_to_id, 'button_status': button_status } return render(request, 'rate.html', context)
def demo_rate(request, demoid): context = RequestContext(request) context_dict = {} t = get_team(request.user) add_isteam_to_context_dict(context_dict, t) rater = get_rater(request.user) if rater: if request.method == 'POST': rating_form = RatingForm(data=request.POST) if rating_form.is_valid(): demo = Demo.objects.get(id=demoid) # check if the rater has already rated this app, if so, remove this entry and replace with new rating rating_check = Rating.objects.filter(rater=rater, demo=demo).count() if rating_check == 1: past_rating = Rating.objects.get(rater=rater, demo=demo) demo.rating_count = demo.rating_count - 1 demo.rating_sum = demo.rating_sum - past_rating.score past_rating.delete() demo.save() rating = rating_form.save(commit=False) rating.rater = rater rating.demo = demo rating.save() demo.rating_count = demo.rating_count + 1 demo.rating_sum = demo.rating_sum + rating.score demo.save() return HttpResponseRedirect('/showcase/demo/show/' + str(demoid) + '/') else: print rating_form.errors else: rating_form = RatingForm() context_dict['rating_form'] = rating_form return render_to_response('showcase/demo.html', context_dict, context) return HttpResponseRedirect('/showcase/demo/show/' + str(demoid) + '/')
def practice_flashcards(request, mode='', template_name='practice_flashcards.html'): """ Practice a flashcard. """ # Get the latest element you should practice practices = FlashCard.by_practice.filter(user=request.user) if len(practices) == 0: return render_to_response(template_name, {'errors': ['No items to practice']}, context_instance=RequestContext(request)) practice = practices[0] form = RatingForm(initial={'id': practice.id}) # Multiple choice practice if mode == "multiple": # Return a list with three random flashcard items solutions = FlashCard.objects.all().order_by('?')[:2] return_dict = { 'practice': practice, 'form': form, 'solutions': solutions } # default to "single" else: return_dict = { 'practice': practice, 'form': form, } return render_to_response(template_name, return_dict, context_instance=RequestContext(request))
def demo_show(request, demoid): context = RequestContext(request) #TODO(leifos): add in error handlding and checking, handle gracefully demo = Demo.objects.get(id=demoid) team = demo.team ratings = Rating.objects.filter(demo=demo).order_by('-score') rater = get_rater(request.user) can_rate = False if rater: can_rate = True context_dict = { 'team': team, 'demo': demo, 'ratings': ratings, 'can_rate': can_rate } t = get_team(request.user) add_isteam_to_context_dict(context_dict, t) if can_rate: rate_form = RatingForm() context_dict['rate_form'] = rate_form return render_to_response('showcase/demo.html', context_dict, context)
def api_add_rating(request, course_id): if request.method == 'POST': form = RatingForm(request.POST) results = [] if form.is_valid(): rating = form.save(commit=False) rating.user = UserProfile.objects.get(user=int(request.user.id)) rating.date = datetime.datetime.now() try: c = Course.objects.get(id=int(course_id)) rating.course = c rating.save() #update the course averages c.number_of_ratings += 1 c.average_difficulty = ((c.average_difficulty if c.average_difficulty else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['difficulty_rating'])) \ / Decimal(c.number_of_ratings) c.average_teaching = ((c.average_teaching if c.average_teaching else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['teaching_rating'])) \ / Decimal(c.number_of_ratings) c.average_materials = ( (c.average_materials if c.average_materials else 0) * (c.number_of_ratings - 1) + Decimal(form.cleaned_data['materials_rating'])) / Decimal( c.number_of_ratings) c.average_overall = ((c.average_overall if c.average_overall else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['overall_rating'])) \ / Decimal(c.number_of_ratings) c.average_satisfaction = ((c.average_satisfaction if c.average_satisfaction else 0) * ( c.number_of_ratings - 1) + Decimal(form.cleaned_data['satisfaction_rating'])) \ / Decimal(c.number_of_ratings) c.save() #response contains averages for the course, and the username of the submitter msg = { "data": { "overall": float(c.average_overall), "satisfaction": float(c.average_satisfaction), "difficulty": float(c.average_difficulty), "teaching": float(c.average_teaching), "materials": float(c.average_materials), "ratings": c.number_of_ratings, "username": request.user.username } } results.append(msg) except Exception as e: return HttpResponseRedirect('/') else: print form.errors errors = {"errors": form.errors} results.append(errors) return HttpResponse(json.dumps(results), content_type="application/json") else: return course(request, course_id)
def rating(demand_id, recipient): """ The '/bid/<demand_id>/rating/<recipient>' route is where the user can rate another user for a demand they were involved in. """ if 'username' not in session: return redirect(url_for('login')) demand_info = Demand.get_info(demand_id) # make sure the user is authorized to rate the recipient if session['role'] == 'developer': # developer rates the client, so client is recipient if session['username'] != demand_info['chosen_developer_username']: return render_template('access_denied.html') elif session['role'] == 'client': # client rates the developer, so developer is recipient if session['username'] != demand_info['client_username']: return render_template('access_denied.html') if Rating.check_if_valid_rating_form(int(demand_id), recipient, session['username']): form = RatingForm() if request.method == "GET": return render_template("rating.html", form=form, recipient=recipient, demand_id=demand_id) elif request.method == "POST": # low rating if form.rating.data <= 2: session['rating' + demand_id] = form.rating.data return redirect( url_for('ratingMessage', demand_id=demand_id, recipient=recipient)) elif form.rating.data == None: return render_template('rating.html', form=form, recipient=recipient, demand_id=demand_id) else: # add to form data Rating(demand_id, recipient, session['username'], form.rating.data) # if the client gave a good rating to a developer (<= 3) # the remaining half of the bid amount gets transferred over to the developer if session['role'] == 'client': bid_amount = Demand.get_info( demand_id)['chosen_bid_amount'] Transaction(recipient, session['username'], round(bid_amount / 2, 2)) # update developer's earnings Developer.add_earnings(recipient, bid_amount) return render_template('ratingFinished.html', recipient=recipient) return render_template('access_denied.html')