def xhr_vote_popup(request, lon, lat): p = Point(float(lon), float(lat)) freguesia = CAOPContinente.objects.get(geometry__intersects=p) print("xhr_vote_popup: request.method: %s" % request.method) if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): num_visitors = form.cleaned_data['adicionar_visitantes'] freguesia.visitors += int(num_visitors) freguesia.save() result = HttpResponseRedirect( #reverse('collectvisitors.views.xhr_vote_ok'), reverse('collectvisitors-vote_ok', args=(freguesia.pk,)) ) else: form = VoteForm() result = render_to_response( 'collectvisitors/voteform.html', {'form' : form, 'freguesia' : freguesia}, context_instance=RequestContext(request) ) else: form = VoteForm() result = render_to_response( 'collectvisitors/voteform.html', {'form' : form, 'freguesia' : freguesia}, context_instance=RequestContext(request) ) return result
def detail(request, profile_id): profile = get_object_or_404(Profile, pk=profile_id) if request.method == 'POST' and request.POST['action'] == "create": comment_form = CommentForm(request.POST, ) if comment_form.is_valid(): obj = comment_form.save(commit=False) obj.user = request.user obj.profile = profile obj.save() else: comment_form = CommentForm() if request.method == 'POST' and request.POST['action'] == "vote": try: v = Vote.objects.get(for_whom=profile.owner, from_whom=request.user) vote_form = VoteForm(request.POST, instance=v) except Vote.DoesNotExist: vote_form = VoteForm(request.POST) if vote_form.is_valid(): obj = vote_form.save(commit=False) obj.from_whom = request.user obj.for_whom = profile obj.save() else: vote_form = VoteForm() context = { 'profile': profile, 'comment_form': comment_form, 'vote_form': vote_form, } return render(request, 'profiles/detail.html', context)
def vote(): if get_setting('stage') != 'vote': return redirect(url_for('index')) form = VoteForm() form.selection.choices = split_response() error = False if request.method == 'POST': if not form.validate(): error = '폼을 채워 주세요' else: voter = Voters.query.filter_by(key=form.key.data).first() if not voter: error = '키를 잘못 입력했어요' elif voter.voted: error = '이미 투표하셨네요' else: voter.voted = True vote = Vote(int(form.selection.data)) db.session.add(vote) remain = get_remain() if remain == 0: set_stage('result') base = os.path.abspath(os.path.dirname(__file__)) shutil.copy2(os.path.join(base, 'app.db'), os.path.join(base, 'static/app.db')) db.session.commit() return render_template('result.html', vote=vote, select=list(split_response())[vote.selection][1], remain=remain) form.selection.choices = split_response() return render_template('vote.html', form=form, error=error, remain=get_remain())
def vote(recipe_id): form = VoteForm(request.form) if request.method == 'POST' and form.validate(): vote = Vote.query.filter_by( recipe_id=recipe_id, user_id=current_user.id ).first() if vote: vote.value = int(request.form['value']) else: vote = Vote( value=int(request.form['value']), user_id=current_user.id, recipe_id=recipe_id) db.session.add(vote) db.session.commit() recipe = Recipe.query.filter_by(id=recipe_id).first() recipe.calculate_average() db.session.add(recipe) db.session.commit() flash('Vote added successfully', 'success') return redirect(url_for('all_recipes'))
def vote(id): form = VoteForm(request.form) if request.method == "POST" and form.validate(): if _validate_user(form.facebook_uid.data, form.facebook_token.data): if _make_vote(form.service_id.data, form.facebook_uid.data, form.facebook_name.data): return jsonify(result="success") else: logging.info("could not make vote..") else: logging.info("could not validate user...") else: logging.info(len(form.errors)) for error in form.errors: logging.info(error) return abort(403)
def xhr_vote(request, freg_id): freg_id = int(freg_id) freguesia = CAOPContinente.objects.get(pk=freg_id) print("xhr_vote: request.method: %s" % request.method) if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): #freg_id = form.cleaned_data['freguesia'] num_visitors = form.cleaned_data['adicionar_visitantes'] freguesia.visitors += int(num_visitors) freguesia.save() result = HttpResponseRedirect( #reverse('collectvisitors.views.xhr_vote_ok'), reverse('collectvisitors-vote_ok', args=(freg_id,)) #reverse('collectvisitors-vote', args=(freg_id,)) ) else: form = VoteForm() result = render_to_response( 'collectvisitors/voteform.html', {'form' : form}, context_instance=RequestContext(request) ) else: form = VoteForm() result = render_to_response( 'collectvisitors/voteform.html', {'form' : form, 'freguesia' : freguesia}, context_instance=RequestContext(request) ) return result
def vote(): contest = Contest.query.order_by(Contest.id.desc()).first() path = IMAGE_PATH captions = Caption.query.order_by(Caption.text) user_captions = [a.user_id for a in contest.captions] user = g.user form = VoteForm() form.vote.choices = [(c.id, c.text) for c in contest.captions] choices = form.vote.choices votes = [ a.user_id for a in Vote.query.join(Caption).join(Contest).filter( Contest.id == contest.id) ] if request.method == "POST": vote = int(request.form['vote']) if form.validate_on_submit(): vote = Vote(user_id=g.user.id, caption_id=vote) db.session.add(vote) db.session.commit() flash("Thanks for voting!") return redirect(url_for('vote')) return render_template('vote.html', title="Vote", path=path, captions=captions, contest=contest, form=form, choices=choices, user=user, user_captions=user_captions, votes=votes)
def vote_answer(request, answer_id): answer = get_object_or_404(Answer, id=answer_id) form = VoteForm(request.POST) if not form.is_valid(): return HttpResponseServerError(_("Were you playing with that form?")) Vote.objects.get_or_create(answer=answer, user=request.user, defaults={'value':form.cleaned_data['value']}) return HttpResponseRedirect(reverse('view_question', args=[answer.question.id]))
def question(question_id=None): form = VoteForm() option_list = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] answers_all = Answer.query.filter_by(question_id=question_id).all() if form.is_submitted(): question = Question.query.filter_by(id=question_id) question.vote = form.vote db.session.commit() flash('Vote was added') return redirect(url_for('index')) return render_template('question.html', question_id=question_id, answers=answers_all, form=form, option_list=option_list)
def vote(request): if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): choice = form.cleaned_data.get('choice') choice.votes += 1 choice.save() return render_to_rest({'poll': choice.poll.id, 'choice': choice.id}) else: return render_form_error_to_rest(form) raise Http404
def vote(request, id_num): vf = VoteForm(request.POST or None) post = get_object_or_404(Post, pk=id_num) if vf.is_valid() and request.user.is_authenticated(): user = request.user prev_vote = Vote.objects.filter(user=user, parent_post=post.parent,) if prev_vote.exists(): prev_vote.delete() messages.warning(request, 'Changing your vote because you already voted on some child of the parent post') vote = Vote(post=post, parent_post=post.parent, user=user) vote.save() return HttpResponseRedirect(request.META["HTTP_REFERER"])
def ajax_vote_cast(request, next=None, xhr="WTF?"): """ Cast a vote HTTP POST is required. """ # Fill out some initial data fields from an authenticated user, if present error = "" if request.user.is_anonymous(): return ajax_error("Must be logged in.", "error") if not request.user.get_profile().access_token: error = "Must have access token." return ajax_error(error, "error") data = request.POST.copy() # Look up the object we're trying vote on issue = data.get("issue") if issue is None: error = "Missing issue field." status = simplejson.dumps({'status': 'debug', 'error': error}) return http.HttpResponseServerError(status, mimetype="application/json") # Construct the vote form form = VoteForm(data) # If there are errors report if form.errors: error = "" for e in form.errors: error += "Error in the %s field: %s" % (e, form.errors[e]) status = simplejson.dumps({'status': 'error', 'error': error}) return http.HttpResponse(status, mimetype="application/json") # Otherwise submit the vote to Service Provider if form.is_valid(): retstatus = demo.post_vote(request, form.clean()) else: pass #for now if retstatus != 201: error = "vote cast failed, code %d" % retstatus status = simplejson.dumps({'status': 'debug', 'error': error}) return http.HttpResponseServerError(status, mimetype="application/json") # Save the vote and signal that it was saved status = simplejson.dumps({'status': "success"}) return http.HttpResponse(status, mimetype="application/json")
def submit_vote(): result = { "success" : 0, "message" : "An error occurred" } if phase() != 2: result["message"] = "Not voting phase!" return json.dumps(result), 200 # return 200 so message displays if not current_user.is_authenticated: # rather than login_required, this allows returning a json result["message"] = "Not logged in" return json.dumps(result), 200 # fetch via with_for_update to lock this row user = User.query.filter_by( id=current_user.id).with_for_update().first_or_404() form = VoteForm() if form.validate() or True: try: nom_id = int(form.nomid.data) except: return json.dumps(result), 200 nom = Nomination.query.filter_by(id=nom_id).first() if nom is None: return json.dumps(result), 200 result["no_vote"] = [] rems = set(nom.award.nominations).intersection(user.selections) for rem in rems: # take away vote from other nom in this category # clicking same button will simply remove the vote user.selections.remove(rem) result["no_vote"].append(str(rem.id)) if nom in rems: # we removed the vote, so we are done result["success"] = 1 result["message"] = "Vote removed" else: # only add vote if it was a different nomination's button nom.voters.append(user) result["success"] = 2 result["message"] = "Vote submitted" result["vote"] = str(nom.id) db.session.commit() return json.dumps(result), 200
def smile(): form = VoteForm() if "randomNote" not in session: #this is temporary; once site gets up and going, will find better way to counter botting session["randomNote"] = toJSON(Note.getRandomNote()) if form.validate_on_submit(): tempNote = Note.getNote(session["randomNote"]["lookupId"]) if form.like.data: tempNote.update({"numLikes": tempNote.numLikes + 1}) elif form.dislike.data: tempNote.update({"numDislikes": tempNote.numDislikes + 1}) session.clear() return redirect('/smile') return render_template("smile.html", notez = Note.getNote(session["randomNote"]["lookupId"]), form=form)
def index(request): if not _is_active(): return render_to_response('over.html', {}, context_instance=RequestContext(request)) if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('done')) else: form = VoteForm() return render_to_response('index.html', { 'form': form, }, context_instance=RequestContext(request))
def poll(poll): poll1 = poll.replace('-', ' ') poll1 = poll1.replace('~', '?') vote_form = VoteForm() voted = False var = models.isVoted.query.filter_by(user_id=g.user.id) vote_list = [x for x in var] if vote_list: for vote in vote_list: if vote.poll_id == models.Poll.query.filter_by( body=poll1).first().id: voted = True #vote form ki choice field me choices add (to make a dynamic list for selection) vote_form.choice.choices = [ (str(x.choice_id), str(x.value)) for x in models.Poll.query.filter_by(body=poll1).first().choices.all() ] #adding pie chart c = [x for x in models.Poll.query.filter_by(body=poll1).first().choices] choice_vote = [['choice', 'votes']] for choice in c: choice_vote.append([str(choice), int(choice.votes)]) if vote_form.validate_on_submit(): # add a vote to the choice models.Choice.query.get(vote_form.choice.data).vote() voted = models.isVoted( user_id=g.user.id, poll_id=int(models.Poll.query.filter_by(body=poll1).first().id), option_id=vote_form.choice.data) #update the isVoted table db.session.add(voted) if vote_form.comment.data is not None and vote_form.comment.data != '': comment = models.Comment(choice_id=vote_form.choice.data, user_id=g.user.id, body=vote_form.comment.data, anonymous=vote_form.anonymous.data) db.session.add(comment) db.session.commit() flash('Voted Successfully') return redirect(url_for('poll', poll=poll)) return render_template( 'vote.html', poll=models.Poll.query.filter_by(body=poll1).first(), form=vote_form, voted=voted, choice_vote=choice_vote)
def vote(request, id_num): vf = VoteForm(request.POST or None) post = get_object_or_404(Post, pk=id_num) if request.method == "POST" and vf.is_valid(): if request.user.is_authenticated(): user = request.user else: user = User.objects.get(username="******") vote = Vote(post=post, user=user, ip=request.META["REMOTE_ADDR"]) vote.save() return HttpResponseRedirect(request.META["HTTP_REFERER"]) return render_to_response("vote.html", {"form": vf}, context_instance=RequestContext(request))
def ajax_vote_cast(request, next=None, xhr="WTF?"): """ Cast a vote HTTP POST is required. """ # Fill out some initial data fields from an authenticated user, if present error = "" if request.user.is_anonymous(): return ajax_error( "Must be logged in." , "error" ) if not request.user.get_profile().access_token: error = "Must have access token." return ajax_error( error , "error" ) data = request.POST.copy() # Look up the object we're trying vote on issue = data.get("issue") if issue is None: error = "Missing issue field." status = simplejson.dumps({'status': 'debug', 'error': error}) return http.HttpResponseServerError(status, mimetype="application/json") # Construct the vote form form = VoteForm(data) # If there are errors report if form.errors: error = "" for e in form.errors: error += "Error in the %s field: %s" % (e, form.errors[e]) status = simplejson.dumps({'status' : 'error', 'error' : error }) return http.HttpResponse(status, mimetype="application/json") # Otherwise submit the vote to Service Provider if form.is_valid(): retstatus = demo.post_vote(request, form.clean()) else: pass #for now if retstatus != 201: error = "vote cast failed, code %d" % retstatus status = simplejson.dumps({'status': 'debug', 'error': error}) return http.HttpResponseServerError(status, mimetype="application/json") # Save the vote and signal that it was saved status = simplejson.dumps({'status': "success"}) return http.HttpResponse(status, mimetype="application/json")
def POST(self): form = VoteForm() if not form.validates(): raise web.notfound(form.note) if not web.ctx.game.your_turn: raise web.notfound("It's not your turn!") Comment.insert_or_update( ('game_id', 'user_id', 'seq', 'move'), game_id=web.ctx.game.id, user_id=web.ctx.user.id, seq=web.ctx.game.current_seq, move=form.d.pos, notes=form.d.notes, ip_address=web.ctx.ip, )
def vote(): form = VoteForm() if request.method == 'POST': k = request.form.get('opt1') w = request.form.get('opt2') s = request.form.get('opt3') b = request.form.get('opt4') if k == 'opt1': k = VotePost('opt1') db.session.add(k) if w == 'opt2': w = VotePost('opt2') db.session.add(w) if s == 'opt3': s = VotePost('opt3') db.session.add(s) if b == 'opt4': b = VotePost('opt4') db.session.add(b) db.session.commit() elif request.method == 'GET': return render_template('vote.html', form=form) return redirect("result")
def displayVoteForm(): coll = [] b_id = request.args.get('key') try: conn = mysql.connect() cursor = conn.cursor() session['ballot'] = b_id cursor.callproc('SelectBallotAndChoices', (b_id, )) data = cursor.fetchall() finally: conn.commit() conn.close() bname = data[0][0] prop = data[0][1] #if len(form.picker.choices) == 0: for result in data: coll.append((result[2], result[3])) # form.picker.choices.set_default(result[2]) print coll form = VoteForm() form.picker.choices = coll return render_template("votenow.html", ballot_name=bname, proposal_text=prop, form=form)
def voting(id): """ Render the dashboard template on the /dashboard route """ if request.method == 'POST': vote = Vote.query.get_or_404(id) vote.vaoted_to = request.form.get('field') db.session.add(vote) db.session.commit() return render_template('home/ThankYou.html') vote = Vote.query.get_or_404(id) poll = Poll.query.get_or_404(vote.poll_id) e = poll.electorate if vote.voter_id == current_user.id: if vote.vaoted_to: return render_template('home/dashboard.html', id=current_user.id, title="Dashboard") form = VoteForm(obj=vote) return render_template('home/voting.html', electorate=e, title="Voting") else: return render_template('home/dashboard.html', id=current_user.id, title="Dashboard")
def vote_form(party_id): if not g.user: flash('You must be logged in for that!', category='info') return redirect('/login') party = Party.query.filter_by(id=party_id).first() if not party: flash("We can't find that party", category='danger') return redirect('/404') if g.user not in party.members: flash('You are not a memeber of this party', category='warning') return redirect('/') resturaunts = Resturaunt.query.filter_by(party_id=party.id, voted_out=False).all() yet_to_be_voted = [] for resturaunt in resturaunts: if not Vote.query.filter_by(member_id=g.user.id, resturaunt_id=resturaunt.id).first(): yet_to_be_voted.append(resturaunt) if len(yet_to_be_voted) != 0: form = VoteForm() resturaunt = yet_to_be_voted[0] return render_template('/parties/vote.html', form=form, resturaunt=resturaunt) else: flash("""You're done voting for now, refresh this page to see when the resturaunt is chosen""", category='success') return redirect(f'/parties/{party_id}')
def vove(): form = VoteForm(request.form) if request.method == 'POST' and form.validate(): if voted(form.suggestionid.data,str(session['uuid'])): vote = models.Vote(form.suggestionid.data,str(session['uuid']),form.votestatus.data) vote.status = form.votestatus.data models.db.session.add(vote) models.db.session.commit() flash('Thanks, suggestion down-voted') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) vote = models.Vote(form.suggestionid.data,str(session['uuid']),form.votestatus.data) models.db.session.add(vote) models.db.session.commit() flash('Thanks, suggestion up-voted') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data))
def vote(): print(config_cosmos.COSMOSDB_HOST) form = VoteForm() replaced_document = {} if form.validate_on_submit(): # is user submitted vote client = document_client.DocumentClient( config_cosmos.COSMOSDB_HOST, {'masterKey': config_cosmos.COSMOSDB_KEY}) # Read databases and take first since id should not be duplicated. db = next((data for data in client.ReadDatabases() if data['id'] == config_cosmos.COSMOSDB_DATABASE)) # Read collections and take first since id should not be duplicated. coll = next((coll for coll in client.ReadCollections(db['_self']) if coll['id'] == config_cosmos.COSMOSDB_COLLECTION)) # Read documents and take first since id should not be duplicated. doc = next((doc for doc in client.ReadDocuments(coll['_self']) if doc['id'] == config_cosmos.COSMOSDB_DOCUMENT)) # Take the data from the deploy_preference and increment our database doc[form.deploy_preference.data] = doc[form.deploy_preference.data] + 1 replaced_document = client.ReplaceDocument(doc['_self'], doc) # Create a model to pass to results.html class VoteObject: choices = dict() total_votes = 0 vote_object = VoteObject() vote_object.choices = { "Web Site": doc['Web Site'], "Cloud Service": doc['Cloud Service'], "Virtual Machine": doc['Virtual Machine'] } vote_object.total_votes = sum(vote_object.choices.values()) return render_template('results.html', year=datetime.now().year, vote_object=vote_object) else: return render_template('vote.html', title='Vote', year=datetime.now().year, form=form)
def POST(self): #XXX raise web.notfound("The game has ended. Please refresh your browser.") form = VoteForm() if not form.validates(): raise web.notfound(form.note) if not web.ctx.game.your_turn: raise web.notfound("It's not your turn!") Vote.insert_or_update( ('game_id', 'user_id', 'seq'), game_id=web.ctx.game.id, user_id=web.ctx.user.id, seq=web.ctx.game.current_seq, move=form.d.pos, notes=form.d.notes, ip_address=web.ctx.ip, )
def vote(request, id_num): vf = VoteForm(request.POST or None) post = get_object_or_404(Post, pk=id_num) if vf.is_valid() and request.user.is_authenticated(): user = request.user prev_vote = Vote.objects.filter( user=user, parent_post=post.parent, ) if prev_vote.exists(): prev_vote.delete() messages.warning( request, 'Changing your vote because you already voted on some child of the parent post' ) vote = Vote(post=post, parent_post=post.parent, user=user) vote.save() return HttpResponseRedirect(request.META["HTTP_REFERER"])
def handle_vote(party_id, resturaunt_id): form = VoteForm() if form.validate_on_submit(): yay_or_nay = form.yay_or_nay.data vote = Vote.vote(member=g.user, party_id=party_id, resturaunt_id=resturaunt_id, yay=yay_or_nay) if vote: if vote.party.done_voting(): return redirect(f'/done_voting/{party_id}') return redirect(f'/vote/{party_id}') else: flash("""You're done voting for now, refresh this page to see when the resturaunt is chosen""", category='success') return redirect(f'/parties/{party_id}') return redirect(f'/vote/{party_id}')
def poll(poll): poll1=poll.replace('-', ' ') poll1=poll1.replace('~', '?') vote_form=VoteForm() voted=False var=models.isVoted.query.filter_by(user_id=g.user.id) vote_list=[x for x in var] if vote_list: for vote in vote_list: if vote.poll_id==models.Poll.query.filter_by(body=poll1).first().id: voted=True #vote form ki choice field me choices add (to make a dynamic list for selection) vote_form.choice.choices=[(str(x.choice_id), str(x.value)) for x in models.Poll.query.filter_by(body=poll1).first().choices.all()] #adding pie chart c=[x for x in models.Poll.query.filter_by(body=poll1).first().choices] choice_vote=[['choice', 'votes']] for choice in c: choice_vote.append([str(choice), int(choice.votes)]) if vote_form.validate_on_submit(): # add a vote to the choice models.Choice.query.get(vote_form.choice.data).vote() voted=models.isVoted( user_id=g.user.id, poll_id=int(models.Poll.query.filter_by(body=poll1).first().id), option_id=vote_form.choice.data ) #update the isVoted table db.session.add(voted) if vote_form.comment.data is not None and vote_form.comment.data != '': comment=models.Comment( choice_id=vote_form.choice.data, user_id=g.user.id, body=vote_form.comment.data, anonymous=vote_form.anonymous.data ) db.session.add(comment) db.session.commit() flash('Voted Successfully') return redirect(url_for('poll',poll=poll)) return render_template('vote.html',poll=models.Poll.query.filter_by(body=poll1).first(), form=vote_form, voted=voted, choice_vote=choice_vote)
def show_recipe(recipe_id): # TODO: check if the user can view this particular recipe - # is public or recipe.user_id=current_user.id recipe = Recipe.query.get(recipe_id) vote = Vote.query.filter_by(recipe_id=recipe.id, user_id=current_user.id).first() form = VoteForm() if vote: form.value.data = str(vote.value) return render_template('recipes/show.html', recipe=recipe, form=form)
def vote(): form = VoteForm() replaced_document ={} if form.validate_on_submit(): # is user submitted vote client = document_client.DocumentClient(config.DOCUMENTDB_HOST, {'masterKey': config.DOCUMENTDB_KEY}) # Read databases and take first since id should not be duplicated. db = next((data for data in client.ReadDatabases() if data['id'] == config.DOCUMENTDB_DATABASE)) # Read collections and take first since id should not be duplicated. coll = next((coll for coll in client.ReadCollections(db['_self']) if coll['id'] == config.DOCUMENTDB_COLLECTION)) # Read documents and take first since id should not be duplicated. doc = next((doc for doc in client.ReadDocuments(coll['_self']) if doc['id'] == config.DOCUMENTDB_DOCUMENT)) # Take the data from the deploy_preference and increment our database doc[form.deploy_preference.data] = doc[form.deploy_preference.data] + 1 replaced_document = client.ReplaceDocument(doc['_self'], doc) # Create a model to pass to results.html class VoteObject: choices = dict() total_votes = 0 vote_object = VoteObject() vote_object.choices = { "Web Site" : doc['Web Site'], "Cloud Service" : doc['Cloud Service'], "Virtual Machine" : doc['Virtual Machine'] } vote_object.total_votes = sum(vote_object.choices.values()) return render_template( 'results.html', year=datetime.now().year, vote_object = vote_object) else : return render_template( 'vote.html', title = 'Vote', year=datetime.now().year, form = form)
def index(request): """ Handle post requests or list recent feedback messages. """ # Check if this is a post request with new feedback. feedback_form = FeedbackForm(request.POST or None) if feedback_form.is_valid(): return submit(request, page=feedback_form.cleaned_data['page'], message=feedback_form.cleaned_data['message']) # Check if this is a post request to vote on a message. vote_form = VoteForm(request.POST or None) if vote_form.is_valid(): return vote(request, vote_form.cleaned_data['vote']) # Check if this is a post request to delete a message. delete_form = DeleteForm(request.POST or None) if delete_form.is_valid(): return delete(request, delete_form.cleaned_data['delete']) # Otherwise, display recent feedback. return render_to_response(request, 'feedback/index.html', locals())
def submit_vote(): result = {"success": 0, "message": "An error occurred"} if phase() != 2: result["message"] = "Not voting phase!" return json.dumps(result), 200 # return 200 so message displays if not current_user.is_authenticated: # rather than login_required, this allows returning a json result["message"] = "Not logged in" return json.dumps(result), 200 form = VoteForm() if form.validate() or True: try: nom_id = int(form.nomid.data) except: return json.dumps(result), 200 nom = Nomination.query.filter_by(id=nom_id).first() if nom is None: return json.dumps(result), 200 for sel in current_user.selections: if sel in nom.award.nominations: # take away vote from other nom in this category # clicking same button will simply remove the vote current_user.selections.remove(sel) result["no_vote"] = str(sel.id) if sel == nom: # we removed the vote, so we are done result["success"] = 1 result["message"] = "Vote removed" db.session.commit() return json.dumps(result), 200 break # only add vote if it was a different nomination's button nom.voters.append(current_user) result["success"] = 2 result["message"] = "Vote submitted" result["vote"] = str(nom.id) db.session.commit() return json.dumps(result), 200
def vote(request, pk): request.session.set_test_cookie() c = {} poll = get_object_or_404(Poll, pk=pk) c.update(csrf(request)) sid = request.session.session_key if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): keyword_field = form.clean_keyword() match = re.match("((?P<poll_pk>\d+)\.)?(?P<keyword>\w+)", keyword_field) keyword = match.group("keyword") choice = poll.choiceByKeyword(keyword=keyword) if choice and WebVote.do_vote(sid, choice): return HttpResponseRedirect("/success/%s/%s/"%(poll.id,choice.id)) else: form = VoteForm(initial={'poll_id':poll.id,'sid_saved':sid}) c['form'] = form return render_to_response('vote.html', c, context_instance=RequestContext(request))
def voting_vote(request,vot_id): voting = get_object_or_404(Voting, pk=vot_id,uprawnieni__user=request.user,od__lte =timezone.now().date(),do__gte=timezone.now().date()) #zmiana na date() x2 if Voter.objects.get(osoba__user=request.user,glosowanie=voting).zaglosowal==True: #juz glosowal przekierowujemy na strone bledu return render(request, 'voteError.html') if request.method == 'POST': # create a form instance and populate it with data from the request: form = VoteForm(request.POST,voting=voting) # check whether it's valid: if form.is_valid(): # zapisanie oddanych glosow for kan in form.getVotingResults(): k = voting.candidate_set.get(osoba=kan) k.wynik=k.wynik+1 k.save() #oddany glos - nie mozna glosowac drugi raz us =voting.voter_set.get(osoba=request.user.profile) us.zaglosowal=True; us.save() return render(request, 'voteSuccess.html',{'voting':voting.nazwa}) # if a GET (or any other method) we'll create a blank form else: form = VoteForm(voting=voting) #form.fields["kandydaci"].queryset = UserProfile.objects.exclude(user=request.user) ##modyfikujemy liste kandydatow return render(request, 'vote.html', {'form': form,'vot_id':voting.id})
def poll_detail(poll_key): poll = Poll.load(poll_key) if request.method == 'POST': choice = poll.choice_by_name(request.form.get('choice')) if choice: choice.register_vote() return redirect(url_for('poll_detail', poll_key=poll.key)) choices = [( choice, VoteForm(choice=choice.name), ) for choice in poll.choices] return render_template('poll_detail.html', poll=poll, choices=choices)
def vote(recipe_id): form = VoteForm(request.form) if request.method == 'POST' and form.validate(): vote = Vote.query.filter_by(recipe_id=recipe_id, user_id=current_user.id).first() if vote: vote.value = int(request.form['value']) else: vote = Vote(value=int(request.form['value']), user_id=current_user.id, recipe_id=recipe_id) db.session.add(vote) db.session.commit() recipe = Recipe.query.filter_by(id=recipe_id).first() recipe.calculate_average() db.session.add(recipe) db.session.commit() flash('Vote added successfully', 'success') return redirect(url_for('show_recipe', recipe_id=recipe_id)) flash('Error: You can\'t give an empty or out of range vote', 'danger') return redirect(url_for('show_recipe', recipe_id=recipe_id))
def vote(): contest = Contest.query.order_by(Contest.id.desc()).first() path = IMAGE_PATH captions = Caption.query.order_by(Caption.text) user_captions = [a.user_id for a in contest.captions] user = g.user form = VoteForm() form.vote.choices = [(c.id, c.text) for c in contest.captions] choices = form.vote.choices votes = [a.user_id for a in Vote.query.join(Caption).join(Contest).filter(Contest.id == contest.id)] if request.method == "POST": vote = int(request.form['vote']) if form.validate_on_submit(): vote = Vote(user_id=g.user.id, caption_id=vote) db.session.add(vote) db.session.commit() flash("Thanks for voting!") return redirect(url_for('vote')) return render_template('vote.html', title="Vote", path=path, captions=captions, contest=contest, form=form, choices=choices, user=user, user_captions=user_captions, votes=votes)
def awards(): p = phase() if p == 0: return render_template("nominees.html", awards=list_awards()) if p == 2: return render_template("voting.html", form=VoteForm(), awards=list_awards()) # else: nominations form = NominationForm() if form.validate_on_submit(): award = Award.query.filter_by(id=form.award_id.data).first_or_404() award.nominations.append(Nomination(name=form.entry.data, creator=current_user)) db.session.commit() flash("Nomination successful!", "success") return redirect(url_for("awards")) return render_template("nominations.html", form=form, awards=list_awards())
def castVote(): form = VoteForm() print form.errors voteExists = False #if form.validate_on_submit(): #print form.cancel.data if form.submit.data: op_select = form.picker.data bal_id = session.get('ballot') try: conn = mysql.connect() cursor = conn.cursor() cursor.callproc('checkForVote', (bal_id, current_user.vid)) data = cursor.fetchall() if len(data) is 0: cursor.callproc('RecordVote', (bal_id, current_user.vid, op_select)) data = cursor.fetchall() else: voteExists = True finally: conn.commit() conn.close() if not voteExists: flash("Your vote was successfully recorded..") else: flash("You have already voted for this ballot!") return redirect(url_for('displayVoteForm', key=bal_id)) elif form.cancel.data: return redirect(url_for('showAGMs'))
def election(request, electionid): election = get_object_or_404(Election, pk=electionid) if not election.isopen: raise Http404("This election is not open (yet)") if election.startdate > date.today(): raise Http404("This election has not started yet") if election.enddate < date.today(): # Election is closed, consider publishing the results if not election.resultspublic: # If user is an admin, show anyway, otherwise throw an error if not request.user.is_superuser: raise Http404("The results for this election isn't published yet.") # Ok, so we do have the results. Use a custom query to make sure we get decently formatted data # and no client-side ORM aggregation curs = connection.cursor() curs.execute("SELECT c.name, sum(v.score) AS score FROM elections_candidate c INNER JOIN elections_vote v ON c.id=v.candidate_id WHERE v.election_id=%(election)s AND c.election_id=%(election)s GROUP BY c.name ORDER BY 2 DESC", { 'election': election.pk, }) res = curs.fetchall() if len(res) == 0: raise Http404('No results found for this election') return render_to_response('elections/results.html', { 'election': election, 'topscore': res[0][1], 'scores': [{'name': r[0], 'score': r[1], 'width': 300*r[1]/res[0][1]} for r in res], }, context_instance=RequestContext(request)) if len(election.candidate_set.all()) <= 0: raise Http404("This election has no candidates!") # Otherwise, we show up the form. This part requires login if not request.user.is_authenticated(): return HttpResponseRedirect("/login/?next=%s" % request.path) try: member = Member.objects.get(user=request.user) # Make sure member has paid if not member.paiduntil: return render_to_response('elections/mustbemember.html', {}, context_instance=RequestContext(request)) # Make sure that the membership hasn't expired if member.paiduntil < date.today(): return render_to_response('elections/mustbemember.html', {}, context_instance=RequestContext(request)) # Verify that the user has been a member for at least 28 days. if member.membersince > election.startdate - timedelta(days=28): return render_to_response('elections/memberfourweeks.html', { 'registered_at': member.paiduntil - timedelta(days=365), 'mustregbefore': election.startdate - timedelta(days=28), 'election': election, }, context_instance=RequestContext(request)) except Member.DoesNotExist: return render_to_response('elections/mustbemember.html', {}, context_instance=RequestContext(request)) if request.method == "POST": form = VoteForm(election, member, data=request.POST) if form.is_valid(): # Save the form form.save() else: # Not a POST, so generate an empty form form = VoteForm(election, member) return render_to_response('elections/form.html', { 'form': form, 'election': election, }, context_instance=RequestContext(request))
def all_recipes(): form = VoteForm() recipes = Recipe.query.filter_by(is_public=True).order_by(Recipe.id.desc()).all() return render_template('recipes/all_recipes.html', recipes=recipes, form=form)
def view_voting(): votes = {} if request.method == 'GET': if 'id' in request.args: uid = request.args.get('id') result = db_session.query(Voting).filter_by(id=uid).first() form = VoteForm() options = db_session.query(Option).filter_by(voting_id=uid).all() choices = [] votes['number'] = {} votes['user'] = 0 for option in options: choices.append((option.id, option.name)) votes['number'][option.name] = db_session.query( VotesUsers).filter_by(option_id=option.id).count() votes['user'] += db_session.query(VotesUsers).filter_by( option_id=option.id).filter_by( user_id=current_user.id).count() form.option.choices = choices if result.end_date + timedelta(1) > date.today( ): #bigger means older votes['end'] = 0 else: votes['end'] = 1 return render_template('voting.html', result=result, form=form, votes=votes, title='cutrenet', subtitle=result.name) elif not current_user.has_role('admin'): flash(u'No tienes permisos para añadir o borrar votaciones', 'error') return redirect('/votaciones', code=302) elif 'add' in request.args: form = VotingForm() return render_template('voting.html', form=form, title='cutrenet', subtitle="new voting") elif 'delete' in request.args: delete = request.args.get('delete') voting = db_session.query(Voting).filter_by(id=delete).first() db_session.delete(voting) db_session.commit() flash(u'Votación eliminada', 'success') return redirect('/votaciones', code=302) else: flash(u'Tienes que seleccionar una votación', 'error') return redirect('/votaciones', code=302) if request.method == 'POST': if 'add' in request.args and current_user.has_role('admin'): voting = Voting() form = VotingForm() if form.validate_on_submit(): voting.name = request.form['name'] voting.description = request.form['description'] voting.start_date = form.start_date.data voting.end_date = form.end_date.data names = request.form['options'].split('|') for name in names: option = Option() option.name = name voting.options.append(option) db_session.add(voting) db_session.commit() flash(u'Votación añadida', 'success') return redirect('votaciones', code=302) return render_template('voting.html', form=form, votes=votes, title='cutrenet', subtitle="new voting") elif 'vote' in request.args: uid = request.args.get('vote') form = VoteForm() options = db_session.query(Option).filter_by(voting_id=uid).all() choices = [] votes['number'] = {} votes['user'] = 0 for option in options: choices.append((option.id, option.name)) votes['number'][option.name] = db_session.query( VotesUsers).filter_by(option_id=option.id).count() votes['user'] += db_session.query(VotesUsers).filter_by( option_id=option.id).filter_by( user_id=current_user.id).count() form.option.choices = choices result = db_session.query(Voting).filter_by(id=uid).first() if result.end_date + timedelta(1) > date.today( ): #bigger means older votes['end'] = 0 else: votes['end'] = 1 if form.validate_on_submit(): if votes['user'] == 0: option = db_session.query(Option).filter_by( id=request.form['option']).first() user = db_session.query(User).filter_by( id=current_user.id).first() option.votes.append(user) db_session.add(option) db_session.commit() votes['user'] = 0 for option in options: votes['number'][option.name] = db_session.query( VotesUsers).filter_by(option_id=option.id).count() votes['user'] = 1 flash(u'Voto registrado', 'success') else: flash(u'Ya has votado, mamón', 'alert') return render_template('voting.html', form=form, result=result, votes=votes, title='cutrenet', subtitle=u"voted ✔️")
def get_poll(poll_id): """View function for get poll page.""" if not utils.valid_session(session): # User couldn't present valid credentials, so generate clean ones. # TODO: Fix DB stuff to do this all at once? cookie_id = db_funcs.new_cookie() cookie_hash = binascii.hexlify(os.urandom(32)).decode("ascii") session["id"] = cookie_id session["votes"] = [] session["cookie_hash"] = cookie_hash session.permanent = True session.modified = True db_funcs.update_cookie(cookie_id, cookie_hash, int(datetime.now().timestamp())) current_app.logger.info("New session instantiated") # If the user looks trustworthy, don't ask them for a captcha. if len(session["votes"]) < 5: form = VoteFormWithCaptcha() else: form = VoteForm() if current_app.config["DEBUG"]: # Recaptcha probably won't work form = VoteForm() # Query database for poll details. row = db_funcs.get_poll(poll_id) if row is None: abort(404) if row["close_date"] < datetime.now().timestamp(): # Poll is expired and should be closed. db_funcs.close_poll(poll_id) generate_results(poll_id) # Redirect to results. return redirect(url_for("polls.get_results", poll_id=poll_id)) # Check if the poll is in the user's voting record already. if poll_id in session["votes"]: already_voted = True else: already_voted = False # TODO: Fix the HTML for that so it isn't awful? # Argh why can't I flash to current request. if request.method == "POST": if already_voted and not current_app.config["ALLOW_REPEAT_VOTES"]: # Users aren't allowed to vote twice. flash("You've already voted on this poll") return redirect(url_for("polls.get_poll", poll_id=poll_id)) if not form.validate_on_submit(): for error_field, errors in form.errors.items(): for error in errors: flash("{0}: {1}".format(error_field, error)) return redirect(url_for("polls.get_poll", poll_id=poll_id)) # TODO: more aggressively deny voting with no credential? # or does CSRF token work alone? # Which choices are recorded in the database? valid_choices = [row["choice_number"] for row in db_funcs.get_choices(poll_id)] choices = [] # User should've sent their choice preferences like 1;2;3;4. # Split and iterate over them. for choice in form.ballot_json.data.split(";"): try: # Is this choice a valid int? And is it in the database? if int(choice) in valid_choices: # If so store it in 'choices'. choices.append(int(choice)) # If not, ignore it. except ValueError: continue if len(choices) == 0: flash("You have to select at least one valid choice") return redirect(url_for("polls.get_poll", poll_id=poll_id)) # Serialise the vote for storage in database. ballot_string = ",".join(map(str, choices)) db_funcs.add_vote(poll_id, ballot_string) # Vote was successfully recorded; add poll to user's voting record. session["votes"].append(poll_id) cookie_hash = binascii.hexlify(os.urandom(32)).decode("ascii") session["cookie_hash"] = cookie_hash session.modified = True db_funcs.update_cookie(session["id"], cookie_hash, int(datetime.now().timestamp())) if row["early_results"]: # Early results enabled for this poll, send user to preview page. return redirect(url_for("polls.get_results", poll_id=poll_id)) else: # Early results not enabled, redirect to homepage. return redirect(url_for("home")) # This is a GET request, prepare template with details for requested poll. title, question = row["title"], row["text"] close_date = datetime.fromtimestamp(row["close_date"]) # TODO: handle more properly if datetime.now() >= close_date: return redirect(url_for("polls.get_results", poll_id=poll_id)) early_results = row["early_results"] choices = {row["choice_number"]: row["text"] for row in db_funcs.get_choices(poll_id)} choices_json = [{"name": v, "num": k} for k, v in choices.items()] return render_template("poll.html", title=title, question=question, choices=choices, close_date=str(close_date), poll_id=poll_id, choices_json=choices_json, early_results=early_results, form=form, already_voted=already_voted)