Exemple #1
0
 def new_vote(self, poll, value=1, **kwargs):
     """ Generate a new vote """
     kwargs["poll"] = poll
     if not "user" in kwargs:
         kwargs["user"] = self.new_user()
     kwargs["value"] = value
     vote = Vote(**kwargs)
     vote.save()
     self._votes.append(vote)
     return vote
Exemple #2
0
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    if request.method == 'GET':
        t = request.GET.get('token', None)
        return display_poll(request, poll=p, token=t)
    try:
        t = Token.objects.get(token=request.POST['token'], poll=p)
    except Token.DoesNotExist:
        return display_poll(request,
                            poll=p,
                            token=None,
                            error_message="The poll token is invalid.")
    try:
        v = Vote.objects.get(token=t, choice__poll=p)
        return display_poll(
            request,
            poll=p,
            token=t,
            error_message=("You can only vote once, and you've already voted"
                           " for %s" % v.choice.choice))
    except Vote.DoesNotExist:
        pass
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return display_poll(request,
                            poll=p,
                            token=t,
                            error_message="You didn't select a choice.")
    else:
        write_in = None
        if selected_choice.choice == 'Other':
            write_in = request.POST.get('write_in', None)
            if not write_in:
                return display_poll(
                    request,
                    poll=p,
                    token=t,
                    error_message="'Other' field can't be blank")

        selected_choice.votes += 1
        selected_choice.save()

        vote = Vote(token=t, choice=selected_choice)
        vote.save()
        t.used = True
        t.save()

        if write_in:
            WriteInChoice.objects.create(choice=write_in, vote=vote)
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('poll_thanks'))
Exemple #3
0
def vote(request):
    c = Choice.objects.filter(pk=request.POST['cid'])
    c = c[0]
    c.votes = c.votes + 1
    c.save()
    p = Poll.objects.filter(pk=request.POST['qid'])
    p = p[0]
    v = Vote(poll=p,
             choice=c,
             user=request.user,
             pub_date=datetime.datetime.now())
    v.save()
    return HttpResponseRedirect("/" + str(p.category.id) + "/" +
                                request.POST['qid'] + "/")
Exemple #4
0
def seed_votes():
    """
   Crée un nouveau vote sur chaque sondage pour chaque utilisateur
    Voté pour le choix est choisi au hasard.
    Supprime tous les votes avant d'en ajouter de nouveaux
    """
    Vote.objects.all().delete()
    users = User.objects.all()
    polls = Poll.objects.all()
    count = 0
    number_of_new_votes = users.count() * polls.count()
    for poll in polls:
        choices = list(poll.choice_set.all())
        for user in users:
            v = Vote(
                user=user,
                poll=poll,
                choice=random.choice(choices)
            ).save()
            count += 1
            percent_complete = count / number_of_new_votes * 100
            print(
                "Adding {} new votes: {:.2f}%".format(
                    number_of_new_votes, percent_complete),
                end='\r',
                flush=True
            )
    print()
Exemple #5
0
def vote(request, poll_id):
    poll = get_object_or_404(Poll, pk = poll_id)
    
    try:
        selected_choice = poll.choice_set.get(pk = request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Missing or invalid choice
        messages.add_message(request, messages.ERROR, 'Missing or invalid choice.')
        
        return HttpResponseRedirect(reverse('poll_details', args = (poll_id,)))
        
    else:
        vote = Vote(choice = selected_choice, ip_address = request.META['REMOTE_ADDR'])
        vote.save()
        
        return HttpResponseRedirect(reverse('poll_results_choice', args = (poll.id, selected_choice.id)))
def seed_votes():
    """
    Creates a new vote on every poll for every user
    Voted for choice is selected random.
    Deletes all votes prior to adding new ones
    """
    Vote.objects.all().delete()
    users = User.objects.all()
    polls = Poll.objects.all()
    count = 0
    number_of_new_votes = users.count() * polls.count()
    for poll in polls:
        choices = list(poll.choice_set.all())
        for user in users:
            v = Vote(
                user=user,
                poll=poll,
                choice=random.choice(choices)
            ).save()
            count += 1
            percent_complete = count / number_of_new_votes * 100
            print(
                "Adding {} new votes: {:.2f}%".format(
                    number_of_new_votes, percent_complete),
                end='\r',
                flush=True
            )
    print()
Exemple #7
0
def ajax_vote(request, poll_id):
    #if request.session.get('has_voted',False):
    #return HttpResponse("You've already voted")
    p = get_object_or_404(Poll, pk=poll_id)
    print "test1"
    vote_id = Vote.objects.filter(poll_id=poll_id)
    print "test2"
    print vote_id
    if request.user.username:
        vote_user = Vote.objects.filter(poll_id=poll_id,
                                        user_name=request.user.username)
    else:
        vote_user = Vote.objects.filter(
            poll_id=poll_id, user_name=request.META.get('REMOTE_ADDR'))
    print "test3"
    print vote_user

    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
        print "test4"
    except (KeyError, Choice.DoesNotExist):
        return HttpResponseServerError("You didn't select a choice to vote")
        print "test4"
    else:
        print "test5"
        if vote_user:
            print "test6"
            if vote_id:
                print "you have submitted vote already"
                return render_to_response(
                    'polls/votes.html', {'num_votes': selected_choice.votes},
                    context_instance=RequestContext(request))
        else:
            print "test"
            if request.user.username:
                print 'test'
                print request.user.username
                print poll_id
                vote_obj = Vote(poll_id=poll_id,
                                user_name=request.user.username)
                vote_obj.save()
            else:
                print 'test2'
                print request.META.get('REMOTE_ADDR')
                print poll_id
                vote_obj = Vote(poll_id=poll_id,
                                user_name=request.META.get('REMOTE_ADDR'))
                vote_obj.save()
            selected_choice.votes += 1
            selected_choice.save()
            #request.session['has_voted'] = True
            num_votes = selected_choice.votes
            print num_votes
            if request.is_ajax():
                return render_to_response(
                    'polls/votes.html', {'num_votes': num_votes},
                    context_instance=RequestContext(request))
Exemple #8
0
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/question_detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
         if len(Vote.objects.filter(
                 question_id=selected_choice.question.id,
                 voter_id=request.user.id)) > 0:
             return render(request, 'polls/question_detail.html', {
                 'question': question,
                 'error_message': "Vous avez déjà voté pour cette question",
             })

         user_vote = Vote()
         user_vote.voter = request.user.profile
         user_vote.choice = selected_choice
         user_vote.question = selected_choice.question
         user_vote.save()
         selected_choice.votes += 1
         selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
         return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Exemple #9
0
def change_vote(request):
    # Data base calls to get the choice, poll, and votes.
    c = Choice.objects.filter(pk=request.POST['cid'])
    c = c[0]
    p = Poll.objects.filter(pk=request.POST['qid'])
    p = p[0]
    v = Vote.objects.filter(poll=p, user=request.user, old=False)
    v = v[0]
    c2 = v.choice

    # Change vote to old.
    if c.id == c2.id:
        return HttpResponseRedirect("/" + str(p.category.id) + "/" +
                                    request.POST['qid'] + "/")
    v.old = True
    v.save()

    # Create a new vote.
    v2 = Vote(poll=p,
              choice=c,
              user=request.user,
              pub_date=datetime.datetime.now())
    v2.save()

    #Create a negative vote for the old choice.
    v3 = NegativeVote(poll=p,
                      choice=c2,
                      user=request.user,
                      pub_date=datetime.datetime.now())
    v3.save()

    # Delete comments under old choice.
    clist = Comment.objects.filter(choice=c2, user=request.user)
    for co in clist:
        llist = Like.objects.filter(user=request.user, comment=co)
        for l in llist:
            l.delete()
        co.delete()
    c2.votes = c2.votes - 1
    c2.save()
    c.votes = c.votes + 1
    c.save()

    return HttpResponseRedirect("/" + str(p.category.id) + "/" +
                                request.POST['qid'] + "/")
def vote(request, poll_id):
	p = get_object_or_404(Poll, pk=poll_id)
	if request.method == 'GET':
		t = request.GET.get('token', None)
		return display_poll(request, poll=p, token=t)
	try:
		t = Token.objects.get(token=request.POST['token'], poll=p)
	except Token.DoesNotExist:
		return display_poll(request, poll=p, token=None,
						error_message="The poll token is invalid.")
	try:
		v = Vote.objects.get(token=t, choice__poll=p)
		return display_poll(request, poll=p, token=t,
			error_message = ("You can only vote once, and you've already voted"
							" for %s" % v.choice.choice))
	except Vote.DoesNotExist:
		pass
	try:
		selected_choice = p.choice_set.get(pk=request.POST['choice'])
	except (KeyError, Choice.DoesNotExist):
		return display_poll(request, poll=p, token=t,
						error_message="You didn't select a choice.")
	else:
		write_in = None
		if selected_choice.choice == 'Other':
			write_in = request.POST.get('write_in', None)
			if not write_in:
				return display_poll(request, poll=p, token=t,
					error_message="'Other' field can't be blank")

		selected_choice.votes += 1
		selected_choice.save()

		vote = Vote(token=t, choice=selected_choice)
		vote.save()
		t.used = True
		t.save()

		if write_in:
			WriteInChoice.objects.create(choice=write_in, vote=vote)
	# Always return an HttpResponseRedirect after successfully dealing
	# with POST data. This prevents data from being posted twice if a
	# user hits the Back button.
	return HttpResponseRedirect(reverse('poll_thanks'))
Exemple #11
0
def vote(request, poll_id):
  poll = get_object_or_404(Poll, pk=poll_id)
  try:
    selected_choice = poll.choice_set.get(pk=request.POST['choice'])
  except (KeyError, Choice.DoesNotExist):
    return render_to_response('polls/slide_poll.html', {
      'poll': poll,
    }, context_instance=RequestContext(request))
  else:
    vote = Vote()
    vote.choice = selected_choice

    if user_is_logged_in(request):
      profile = UserProfile.objects.get(email = request.session['login_email'])
      vote.user_profile = profile
    vote.save()

    return render_to_response('presentations/slide.html', {'slide': poll},
      context_instance=RequestContext(request))
Exemple #12
0
def vote(request, pk):
    """
    Record a vote for a poll question. The selected choice is in the POST body.
    
    Arguments:
        pk = the question id (primary key)
    """
    question_id = pk
    # lookup the question
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        return Http404(f"Question {question_id} does not exist")
    if not question.can_vote():
        return HttpResponse("Voting not allowed for that question", status=403)
    # get the user's choice
    try:
        choice_id = request.POST['choice']
    except KeyError:
        context = {
            'question': question,
            'error_message': "You didn't select a valid choice"
        }
        return render(request, 'polls/detail.html', context)
    try:
        selected_choice = question.choice_set.get(pk=choice_id)
    except Choice.DoesNotExist:
        context = {
            'question': question,
            'error_message': "You didn't select a valid choice"
        }
        return render(request, 'polls/detail.html', context)
    # Does user already have a Vote for this question?
    vote = get_vote_for_user(request.user, question)
    if not vote:
        vote = Vote(user=request.user, choice=selected_choice)
    else:
        # change an existing vote
        vote.choice = selected_choice
    vote.save()
    return HttpResponseRedirect(reverse('polls:results', args=(question_id, )))
Exemple #13
0
def poll_vote(request, poll_id):
    poll = get_object_or_404(Poll, id=poll_id)

    if not poll.user_can_vote(request.user):
        messages.error(
            request,
            "You have already voted on the poll!",
            extra_tags='alert alert-danger alert-dismissible fade show')
        return redirect('polls:list')
    choice_id = request.POST.get('choice')
    if choice_id:
        choice = Choice.objects.get(id=choice_id)
        new_vote = Vote(user=request.user, poll=poll, choice=choice)
        print(new_vote)
        new_vote.save()
    else:
        messages.error(
            request,
            "No Choice Was Selected!",
            extra_tags='alert alert-danger alert-dismissible fade show')
        return redirect('polls:details', poll_id=poll_id)
    return redirect('polls:details', poll_id=poll_id)
Exemple #14
0
def vote(request: HttpRequest, question_id: int):
    question = get_object_or_404(Question, pk=question_id)
    try:
        choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request,
                      'polls/detail.html',
                      context={
                          'question': question,
                          'error_message': "You didn't select a choice."
                      })
    else:
        try:
            # user has already voted
            vote = Vote.objects.get(user=request.user, question=question)
            vote.choice = choice
        except Vote.DoesNotExist:
            # else create a vote
            vote = Vote(question=question, choice=choice, user=request.user)
        vote.save()
        return HttpResponseRedirect(
            reverse('polls:results', args=(question.id, )))
Exemple #15
0
    def setUpClass(cls):
        super(TestVote, cls).setUpClass()
        template = Template(title='template')

        cls.field = Field(
            title='field',
            template=template,
        )

        cls.poll = Poll(
            title='poll',
            template=template,
        )

        cls.vote = Vote(
            poll=cls.poll,
            field=cls.field,
            value=2,
        )
def ajax_vote(request,poll_id):
	#if request.session.get('has_voted',False):
		#return HttpResponse("You've already voted")
	p = get_object_or_404(Poll, pk=poll_id)
	print "test1"
	vote_id = Vote.objects.filter(poll_id = poll_id)
	print "test2"
	print vote_id
	if request.user.username:
		vote_user = Vote.objects.filter(poll_id = poll_id, user_name=request.user.username)
	else:
		vote_user = Vote.objects.filter(poll_id = poll_id, user_name=request.META.get('REMOTE_ADDR'))
	print "test3"
	print vote_user
	
	try:
		selected_choice = p.choice_set.get(pk=request.POST['choice'])
		print "test4"
	except (KeyError, Choice.DoesNotExist):
		return HttpResponseServerError("You didn't select a choice to vote")
		print "test4"
	else:
		print "test5"
		if vote_user:
			print "test6"
			if vote_id:
				print "you have submitted vote already"
				return render_to_response('polls/votes.html',{'num_votes': selected_choice.votes},context_instance=RequestContext(request))
		else:
			print "test"
			if request.user.username:
				print 'test'
				print request.user.username
				print poll_id
				vote_obj = Vote(poll_id = poll_id, user_name = request.user.username)
				vote_obj.save()
			else:
				print 'test2'
				print request.META.get('REMOTE_ADDR')
				print poll_id
				vote_obj = Vote(poll_id = poll_id, user_name = request.META.get('REMOTE_ADDR'))
				vote_obj.save()
			selected_choice.votes += 1
			selected_choice.save()
			#request.session['has_voted'] = True
			num_votes = selected_choice.votes
			print num_votes
			if request.is_ajax():
				return render_to_response('polls/votes.html',{'num_votes':num_votes},context_instance=RequestContext(request))
Exemple #17
0
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    user = request.user

    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice"
        })
    else:
        if not isinstance(user, AnonymousUser) and user.is_active:
            v = Vote()
            v.choice = selected_choice
            v.user = user
            v.save()
            return redirect(reverse('polls:results', args=(p.id, )))
        else:
            return render(request, 'polls/detail.html', {
                'poll': p,
                'error_message': "You are not logged in"
            })
Exemple #18
0
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    if p.type in [p.SIMPLE, p.MULTI]:
        try:
            choice_ids = request.POST.getlist('choice')
        except (KeyError, Choice.DoesNotExist):
            # Redisplay the poll voting form.
            return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
            })
        else:
            try:
                voter = Voter.objects.get(user=request.user, poll=p)
            except Voter.DoesNotExist:
                voter = Voter(poll=p, user=request.user)
                voter.save()
            for vote in voter.vote_set.all():
                vote.delete()
            for id in choice_ids:
                choice = p.choice_set.get(pk=id)
                vote = Vote(voter=voter)
                vote.choice = choice
                vote.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
    elif p.type == p.RANKED:
        try:
            voter = Voter.objects.get(user=request.user, poll=p)
        except Voter.DoesNotExist:
            voter = Voter(poll=p, user=request.user)
            voter.save()
        for vote in voter.vote_set.all():
            vote.delete()
        rank = request.POST.get('rank').split(',')
        for i,e in enumerate(rank):
            choice = p.choice_set.get(pk=e)
            vote = Vote(voter=voter)
            vote.choice = choice
            vote.ranking = i;
            vote.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
    else:
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "Poll not implemented :(",
            })
Exemple #19
0
 def post(self, request, *args, **kwargs):
     o = Vote()
     o.data = json.loads(request.POST['vote'])
     o.save()
     return HttpResponse("OK")
Exemple #20
0
 def post(self, request, *args, **kwargs):
     o = Vote(poll=self.get_object())
     o.data = json.loads(request.POST['vote'])
     o.save()
     return redirect(o.poll.get_result_url())
Exemple #21
0
def ajax_vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    id_data = list(question.choice_set.all().values('question_id', 'id'))
    print('starting ajax_vote')

    if request.COOKIES.get('q_voted'):
        value = urllib.parse.unquote_plus(request.COOKIES['q_voted'])
        cookie_value = json.loads(value)
        print(cookie_value)
        for q_id in cookie_value['question_id']:
            if q_id == question_id:
                return JsonResponse({'id_data': id_data}, status=400)
    else:
        cookie_value = {'question_id': []}

    try:
        print('Entering try...selecting choice')
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        print('Entering except...choice does not exist')
        return JsonResponse("Choice does not exist.", safe=False, status=400)
    else:
        print('Entering else...success!')
        #selected_choice.update(votes=F('votes') + 1)
        selected_choice.votes = F('votes') + 1
        #selected_choice.votes += 1
        selected_choice.save()

        ipaddress = get_ipaddress(request)
        #ipaddress = '8.8.8.8'
        country_code, country_name, city = get_geodata(ipaddress)

        #print(request.ipinfo.all)
        new_vote = Vote(question=question,
                        choice=selected_choice,
                        ip_address=ipaddress,
                        country_code=country_code,
                        country_name=country_name,
                        city=city)

        new_vote.save()

        question.update_figure()
        plot = question.plot_set.get(question_id=question_id)
        plotly_plot = plot.figure

        # Don't use cookies in dev mode
        if settings.DEBUG:
            return JsonResponse({
                'id_data': id_data,
                'plotly_plot': plotly_plot
            })
        else:
            response = JsonResponse({
                'id_data': id_data,
                'plotly_plot': plotly_plot
            })
            cookie_value['question_id'].append(question_id)
            response.set_cookie("q_voted",
                                value=json.dumps(cookie_value),
                                expires=last_day_of_month())
            return response
Exemple #22
0
 def test_string_representation(self):
     """Verifies calling the __str__ method returns the expected string."""
     task = Vote(value="5", user=self.user, task=self.task)
     self.assertEqual(str(task), 'Task 1 - 5 - testuser')