Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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}')
Ejemplo n.º 6
0
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 ✔️")