Example #1
0
def vote_poem(request, poem_id=None):
    poem = Poem.objects.get(id=poem_id)
    rating = 0
    user = None

    if request.user.is_authenticated():
        user = request.user
    else:
        return HttpResponseRedirect(reverse('poem_detail_view',
                                            args=(poem.id,)))

    ct = ContentType.objects.get_for_model(poem)

    if Vote.objects.filter(content_type__pk=ct.id, object_id=poem_id, user=user).count() > 0:
        return HttpResponseRedirect(reverse('poem_detail_view',
                                            args=(poem.id,)))

    if poem.rating:
        rating = poem.rating
    if request.method == 'POST':
        if 'plus' in request.POST:
            rating = rating + 1
        else:
            rating = rating - 1

        poem.rating = rating
        poem.save()

        vote = Vote(content_object=poem, rating=rating, user=user)
        vote.save()

    return HttpResponseRedirect(reverse('poem_detail_view',
                                        args=(poem.id,)))
Example #2
0
def _update_vote_count(request, votecount, direction):
    '''
    Evaluates a request's Vote and corresponding VoteCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Vote.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Vote; returns False if not.
    '''
    user = request.user
    ip_address = get_ip(request)

    net_change = 0

    # TODO: Rate-limit users based on IP to avoid spamming
    #votes_per_ip_limit = getattr(settings, 'VOTECOUNT_VOTES_PER_IP_LIMIT', 0)
    # check limit on votes from a unique ip address (VOTECOUNT_VOTES_PER_IP_LIMIT)
    #if votes_per_ip_limit:
    #    if qs.filter(ip_address__exact=ip_address).count() > votes_per_ip_limit:
    #        return net_change, False

    # Check if the user already voted
    try:
        prev_vote = Vote.objects.get(user=user, votecount=votecount)

        # SLOW: Instead of deleting the old and creating a new vote, we really
        # should just alter the old vote's direction and then change the
        # VoteCounts total accordingly. The VoteCount change should be done
        # in the overridden save() method

        # Since the user already voted, remove it. Then check if the new vote
        # is in a different direction, and if so, create that one
        prev_direction = prev_vote.direction
        prev_vote.delete()
        net_change -= prev_direction

        if prev_direction != direction:
            # TODO: Is there a better way to refresh this? Like in save()/delete() methods?
            # Reload VoteCount from DB since the previous delete() just changed its up/downvote totals
            votecount = VoteCount.objects.get(id=votecount.id)

            vote = Vote(votecount=votecount,
                        direction=direction,
                        ip_address=get_ip(request))
            vote.user = user
            vote.save()
            net_change += direction
    except Vote.DoesNotExist:
        vote = Vote(votecount=votecount,
                    direction=direction,
                    ip_address=get_ip(request))
        vote.user = user
        vote.save()
        net_change += direction

    return net_change, True
Example #3
0
def _insert_or_update_vote(cart, category, team):
    try:
        vote = Vote.objects.get(cart=cart, category=category)
        if team is None:
            vote.delete()
        else:
            vote.team = team
            vote.save()
    except:
        if team is not None:
            vote = Vote(cart=cart, category=category, team=team)
            vote.save()
Example #4
0
def _insert_or_update_vote(cart, category, team):
    try:
        vote = Vote.objects.get(cart=cart, category=category)
        if team is None:
            vote.delete()
        else:
            vote.team = team
            vote.save()
    except:
        if team is not None:
            vote = Vote(cart=cart, category=category, team=team)
            vote.save()
Example #5
0
def section_find_winner(section):
    win_threshold = Voter.count_eligible() * section.majority_for_change
    
    first_votes = {}
    for c in section.change_set.all():
        first_votes[c] = Vote.do_count(section.id, c.id, 1)

    while True:                
        lowest_count, lowest_c = None, None
        tuple_list = list(first_votes.items())
        tuple_list.sort(key=lambda x: x[1])
        
        highest_count = tuple_list[len(tuple_list)-1][1]
        if highest_count >= win_threshold:
            top = [t[0] for t in tuple_list if t[1] == highest_count]
            return section_tie_break(section, top)
        
        lowest_count = tuple_list[0][1]
        elim_cands = [t[0] for t in tuple_list if t[1] == lowest_count]
        lowest_c, _ = section_tie_break(section, elim_cands, find_worst=True)
                    
        # re-assign votes for lowest_c to next pref - TODO: optimize!
        for orig_vote in Vote.objects.filter(section=section, change=lowest_c):
            alternates = Vote.objects.filter(voter=orig_vote.voter, section=section, priority__gt=orig_vote.priority)
            if len(alternates) > 0:
                alt = alternates[0].change
                if alt not in first_votes:
                    first_votes[alt] = 0
                first_votes[alt] += 1
        
        # eliminate lowest_c
        del first_votes[lowest_c]
        
        if len(first_votes) == 0:
            return (None, None)
Example #6
0
 def get(self):
     election = self.election()
     if not election:
         return
     user = users.get_current_user()
     candidates = db.GqlQuery(
         "SELECT * FROM Candidate WHERE ANCESTOR IS :1", election)
     vote = Vote.get_by_key_name(self._vote_key(election, user))
     if vote:
         entries = dict((c.key().id(), c) for c in candidates)
         keys = [[int(key) for key in rank.split(",")]
                 for rank in vote.ranks.split(";")]
         ranks = interleave(repeat([]), ([entries[key] for key in rank]
                                         for rank in keys))
         unranked = [
             entries[key] for key in entries
             if key not in set(sum(keys, []))
         ]
     else:
         ranks = [[]]
         unranked = candidates
     self.render("vote.html",
                 election=election,
                 ranks=ranks,
                 unranked=unranked)
Example #7
0
 def post(self):
     election = self.election()
     user = users.get_current_user()
     
     # Parse the form input into a reasonable vote set.
     ranks = defaultdict(set)
     for param in self.request.params:
         candidate = param[1:]
         if param[0] == "c" and candidate.isdigit():
             rank = int(self.request.get(param))
             if rank:
                 ranks[rank].add(candidate)
     ranked = ";".join(",".join(sorted(ranks[key])) for key in sorted(ranks))
     
     if ranked:
         # Todo: Use a single transaction for this whole thing,
         # folding the get_or_insert part into the transaction.
         vote = Vote.get_or_insert(self._vote_key(election, user),
             election=election, voter=user, ranks=ranked)
         if vote.ranks != ranked:
             vote.ranks = ranked
             vote.modified = datetime.now()
             vote.put()
     
     self.redirect("/%s/results" % election.key().name())
Example #8
0
    def post(self):
        election = self.election()
        user = users.get_current_user()

        # Parse the form input into a reasonable vote set.
        ranks = defaultdict(set)
        for param in self.request.params:
            candidate = param[1:]
            if param[0] == "c" and candidate.isdigit():
                rank = int(self.request.get(param))
                if rank:
                    ranks[rank].add(candidate)
        ranked = ";".join(",".join(sorted(ranks[key]))
                          for key in sorted(ranks))

        if ranked:
            # Todo: Use a single transaction for this whole thing,
            # folding the get_or_insert part into the transaction.
            vote = Vote.get_or_insert(self._vote_key(election, user),
                                      election=election,
                                      voter=user,
                                      ranks=ranked)
            if vote.ranks != ranked:
                vote.ranks = ranked
                vote.modified = datetime.now()
                vote.put()

        self.redirect("/%s/results" % election.key().name())
Example #9
0
    def test_vote_model(self):
        vote = Vote()
        vote.object_id = self.article._get_pk_val()
        vote.content_type = ContentType.objects.get_for_model(self.article)
        #vote.content_object = ContentType.objects.get_for_model(self.article)

        vote.voter = self.user1
        vote.vote = UPVOTE

        vote.save()

        vote_obj = Vote.objects.all()[0]
        self.assertEqual(vote_obj._get_pk_val(), vote._get_pk_val(),
                         "Primary Keys do not match")
        self.assertEqual(vote.vote, vote_obj.vote, "Vote value does not match")
Example #10
0
def _update_vote_count(request, votecount, direction):
    '''
    Evaluates a request's Vote and corresponding VoteCount object and,
    after a bit of clever logic, either ignores the request or registers
    a new Vote.

    This is NOT a view!  But should be used within a view ...

    Returns True if the request was considered a Vote; returns False if not.
    '''
    user = request.user
    ip_address = get_ip(request)
    
    net_change = 0

    # TODO: Rate-limit users based on IP to avoid spamming
    #votes_per_ip_limit = getattr(settings, 'VOTECOUNT_VOTES_PER_IP_LIMIT', 0)
    # check limit on votes from a unique ip address (VOTECOUNT_VOTES_PER_IP_LIMIT)
    #if votes_per_ip_limit:
    #    if qs.filter(ip_address__exact=ip_address).count() > votes_per_ip_limit:
    #        return net_change, False

    # Check if the user already voted
    try:
        prev_vote = Vote.objects.get(user=user, votecount=votecount)
        
        # SLOW: Instead of deleting the old and creating a new vote, we really
        # should just alter the old vote's direction and then change the 
        # VoteCounts total accordingly. The VoteCount change should be done
        # in the overridden save() method
        
        # Since the user already voted, remove it. Then check if the new vote
        # is in a different direction, and if so, create that one
        prev_direction = prev_vote.direction
        prev_vote.delete()
        net_change -= prev_direction
        
        if prev_direction != direction:
            # TODO: Is there a better way to refresh this? Like in save()/delete() methods?
            # Reload VoteCount from DB since the previous delete() just changed its up/downvote totals
            votecount = VoteCount.objects.get(id=votecount.id)
            
            vote = Vote(votecount=votecount, direction=direction, ip_address=get_ip(request))
            vote.user = user
            vote.save()
            net_change += direction
    except Vote.DoesNotExist:
        vote = Vote(votecount=votecount, direction=direction, ip_address=get_ip(request))
        vote.user = user
        vote.save()
        net_change += direction

    return net_change, True
Example #11
0
def vote(request):
    if request.method == 'POST':
	vote = {'up': 1, 'down': -1}[request.POST.get('vote')]
	djct = int(request.POST.get('djct'))
	djoi = int(request.POST.get('djoi'))
	ct = get_object_or_404(ContentType, pk=djct)
	try:
	    v = Vote.objects.get(user=request.user, content_type=ct, object_id=djoi)
	except Vote.DoesNotExist:
	    v = Vote(user=request.user, content_type=ct, object_id=djoi)
	model = ct.model_class()
	obj = get_object_or_404(model, pk=djoi)
	if v.vote != vote:
	    v.vote = vote
	    v.save()
	if request.is_ajax():
	    return HttpResponse()
	else:
	    return redirect(obj.get_absolute_url())
Example #12
0
def section_tie_break(section, change_list, find_worst=False):
    if len(change_list) == 0:
        raise Exception('av tie break given empty change_list')
    #print('section tie break: ' + ' '.join([c.name for c in change_list]))
    
    change_tuples = []
    for change in change_list:
        prefs = Vote.do_count(section.id, change.id)
        change_tuples.append((change, prefs))
        
    #print('section tie break: ' + str(change_tuples))
    return tie_break(change_tuples, find_worst)
Example #13
0
def yes_or_no(request, verse_id):
    verse = Verse.objects.get(id=verse_id)
    rating = 0
    user = None
    is_admin = False
    if request.user.is_authenticated():
        user = request.user
    else:
        return HttpResponseRedirect(reverse('poem_detail_view',
                                            args=(verse.poem.id,)))

    ct = ContentType.objects.get_for_model(verse)

    if Vote.objects.filter(content_type__pk=ct.id, object_id=verse_id, user=user).count() > 0:
        return HttpResponseRedirect(reverse('poem_detail_view',
                                            args=(verse.poem.id,)))

    if verse.rating:
        rating = verse.rating
    if request.method == 'POST':
        if 'plus' in request.POST:

            rating = rating + 1
            if verse.poem.owner_accept_verse == False and verse.is_accepted == False and rating >= verse.poem.enough_pluses:
                verse.is_accepted = True
        else:
            rating = rating - 1
            if verse.poem.owner_accept_verse == False and verse.is_accepted == False and rating < 0 and abs(
                    rating) >= verse.poem.enough_pluses:
                verse.delete()
                return HttpResponseRedirect(reverse('poem_detail_view',
                                                    args=(verse.poem.id,)))
        verse.rating = rating
        verse.save()

        vote = Vote(content_object=verse, rating=rating, user=user)
        vote.save()

    return HttpResponseRedirect(reverse('poem_detail_view',
                                        args=(verse.poem.id,)))
Example #14
0
 def test_vote_model(self):
     vote = Vote()
     vote.object_id = self.article._get_pk_val()
     vote.content_type = ContentType.objects.get_for_model(self.article)
     #vote.content_object = ContentType.objects.get_for_model(self.article)
     
     vote.voter = self.user1
     vote.vote = UPVOTE
     
     vote.save()
     
     vote_obj = Vote.objects.all()[0]
     self.assertEqual(vote_obj._get_pk_val(), vote._get_pk_val(), "Primary Keys do not match")
     self.assertEqual(vote.vote, vote_obj.vote, "Vote value does not match")
Example #15
0
    def get_similar_items_from_model(self,
                                     item,
                                     user_list,
                                     model,
                                     min_value=MIN_SIMILARITY_VALUE):
        user_item_matrix = self.create_matrix_from_model(user_list, model)
        item_user_matrix = self.rotate_matrix(user_item_matrix)
        #	assert False, (user_item_matrix, item_user_matrix)
        sim_list = []
        item_list = model.objects.all()
        for other in item_list:
            if item == other: continue
            #	    assert False, item_user_matrix[item.id]
            #            sim=utils.distance_matrix_p1_p2(item_user_matrix[item.id],item_user_matrix[other.id]) #returns a 0..1 value
            sim = utils.distance_matrix_p1_p2(
                item_user_matrix.get(item.id, {1: Vote()}),
                item_user_matrix.get(other.id, {1: Vote()}))
            """
            sim=utils.distance_matrix_p1_p2(item_user_matrix.get(item.id,
			{1:Vote(	object=item,
				object_id=item.id,
				user=user_list[0],
				vote=0,
				content_type=ContentType.objects.get_for_model(item)
			)}),
		item_user_matrix.get(other.id, 
			{1:Vote(	object=item,
				object_id=item.id,
				user=user_list[0],
				vote=0,
				content_type=ContentType.objects.get_for_model(item)
			)}
		)) #returns a 0..1 value
	    """
            if sim > min_value:
                sim_list.append((sim, other))

        assert False, sim_list
        sim_list.sort(reverse=True)
        return sim_list
Example #16
0
def index(request):
	context={}
	if request.method=='POST':
		form = voteForm(request.POST)
		if form.is_valid():
			candidates=Candidate.objects.filter(region=Voter.objects.get(id=request.session['id']).region).values_list('id')
			for candidate in candidates:
				if(candidate[0]==form.cleaned_data['candidate']):
					voted=Vote(voter=request.session['id'],candidate=form.cleaned_data['candidate'])
					candidate=Candidate.objects.get(id=form.cleaned_data['candidate'])
					candidate.votes=int(candidate.votes)+1
					candidate.save()
					voted.save()
					return HttpResponse('Success')
			context['error']="Enter valid id"
			return render(request,'voting/index.html',context)
	voterid=example_search.pro()
	context['showform']=1
	if voterid <0:
            voterid=100
            context['showform']=0
	context['voter']=Voter.objects.get(finger=voterid)
	
	print('*************************************')
	if ((datetime.now(timezone.utc)-context['voter'].dob).total_seconds()/(365*86400)<18):
            context['error']="Underage bitch"
            context['showform']=0
	print(context['voter'].finger)
	check=Vote.objects.filter(voter=context['voter'].id)
	print(len(check))
	if(len(check)>0):
           context['error']="Already Voted"
           context['showform']=0
	request.session['id']=context['voter'].id
	candidates=Candidate.objects.filter(region=context['voter'].region).values_list('id','name')
	context['candidates']=candidates
	form = voteForm()
	context['form']=form
	return render(request,'voting/index.html',context)
Example #17
0
File: views.py Project: ahinz/NVOX
def vote(request, amt):
    if request.user is not None and request.user.is_authenticated():
        user = request.user
        req = request.REQUEST

        p = Project.objects.get(pk=req["project"])
        
        votes = Vote.objects.filter(user=user,project=p).all()
        if votes is None or len(votes) == 0:
            vote = Vote(location="!", contribution=amt, project=p, user=user)
        else:
            vote = votes[0]
            vote.contribution = amt

        
        vote.save()
        
        if req["format"] == "json":
            return HttpResponse("{ \"success\": true, \"votes\": %s }" % p.votes(), mimetype="application/json")
        else:
            return redirect('/')
    else:
        return HttpResponse("{ \"success\": false }",mimetype="application/json")
Example #18
0
def vote_literature(request, literature_id=None):
    literature = Literature.objects.get(id=literature_id)
    rating = 0
    user = None

    if request.user.is_authenticated():
        user = request.user
    else:
        return HttpResponseRedirect(reverse('literature_detail_view',
                                            args=(literature.id,)))

    ct = ContentType.objects.get_for_model(literature)

    if Vote.objects.filter(content_type__pk=ct.id, object_id=literature_id, user=user).count() > 0:
        return HttpResponseRedirect(reverse('literature_detail_view',
                                            args=(literature.id,)))

    if literature.rating:
        rating = literature.rating
    if request.method == 'POST':
        if 'plus' in request.POST:
            rating = rating + 1
        else:
            rating = rating - 1

        literature.rating = rating
        literature.save()

        vote = Vote(content_object=literature, rating=rating, user=user)
        vote.save()
        url_par = ""
        if request.POST.get('chapter'):
            chapter_id = request.POST.get('chapter')
            url_par = "?chapter=%s" % chapter_id
    return HttpResponseRedirect(reverse('literature_detail_view',
                                        args=(literature.id,)) + url_par)
Example #19
0
def vote_fanfiction(request, fanfiction_id=None):
    fanfiction = Fanfiction.objects.get(id=fanfiction_id)
    rating = 0
    user = None

    if request.user.is_authenticated():
        user = request.user
    else:
        return HttpResponseRedirect(reverse('fanfiction_detail_view',
                                            args=(fanfiction.id,)))

    ct = ContentType.objects.get_for_model(fanfiction)

    if Vote.objects.filter(content_type__pk=ct.id, object_id=fanfiction_id, user=user).count() > 0:
        return HttpResponseRedirect(reverse('fanfiction_detail_view',
                                            args=(fanfiction.id,)))

    if fanfiction.rating:
        rating = fanfiction.rating
    if request.method == 'POST':
        if 'plus' in request.POST:
            rating = rating + 1
        else:
            rating = rating - 1

        fanfiction.rating = rating
        fanfiction.save()

        vote = Vote(content_object=fanfiction, rating=rating, user=user)
        vote.save()
        url_par = ""
        if request.POST.get('chapter'):
            chapter_id = request.POST.get('chapter')
            url_par = "?chapter=%s" % chapter_id
    return HttpResponseRedirect(reverse('fanfiction_detail_view',
                                        args=(fanfiction.id,)) + url_par)
Example #20
0
def trigger(request):
    account_sid = "ACb53930b6ce7c4b42f4a5c36d49a935b6"
    auth_token  = "06067fefdd853719c721ee6235b2215d"
    client = TwilioRestClient(account_sid, auth_token)

    resource_uri = "/2010-04-01/Accounts/ACb53930b6ce7c4b42f4a5c36d49a935b6/messages/"
    messages = client.messages.list()
    # convert current dates to timestamps, college messages
    for x in messages: 
        x.date_created = x.date_created = datetime(*parsedate_tz(x.date_created)[:-3])
        try:
            int(x.body)
        except ValueError:
            continue 
        if(int(x.body) > 3000 or int(x.body)< 3101):
            try:
                s = Song.objects.get(songId=x.body)
            except Song.DoesNotExist:
                raise CommandError('Song "%s" does not exist' % poll_id)
            v = Vote(number=x.from_,song_id=s)
            v.save() 

    
    return HttpResponse(status=200)
Example #21
0
    def handle(self, *args, **options):
        account_sid = "ACec0c7c5211527b56dedd223ea469e3bc"
        auth_token  = "a79b8b5c99c2cf699782fe2026cf1036"
        client = TwilioRestClient(account_sid, auth_token)

        resource_uri = "/2010-04-01/Accounts/ACec0c7c5211527b56dedd223ea469e3bc/messages/"

        messages = client.messages.list()

    # convert current dates to timestamps, college messages
        for x in messages: 
            x.date_created = x.date_created = datetime(*parsedate_tz(x.date_created)[:-3])
            try:
                int(x.body)
            except ValueError:
                continue 
            if(int(x.body) > 3000 or int(x.body)< 3101):
                try:
                    s = Song.objects.get(songId=x.body)
                except Song.DoesNotExist:
                    raise CommandError('Song "%s" does not exist' % poll_id)
                print("create")
                v = Vote(number=x.from_,song_id=s)
                v.save()
Example #22
0
 def get(self):
     election = self.election()
     if not election:
         return
     user = users.get_current_user()
     candidates = db.GqlQuery("SELECT * FROM Candidate WHERE ANCESTOR IS :1", election)
     vote = Vote.get_by_key_name(self._vote_key(election, user))
     if vote:
         entries = dict((c.key().id(), c) for c in candidates)
         keys = [[int(key) for key in rank.split(",")] for rank in vote.ranks.split(";")]
         ranks = interleave(repeat([]), ([entries[key] for key in rank] for rank in keys))
         unranked = [entries[key] for key in entries if key not in set(sum(keys, []))]
     else:
         ranks = [[]]
         unranked = candidates
     self.render("vote.html", election=election, ranks=ranks, unranked=unranked)
    def setUp(self):
        super(TestValidationStrictlyComment, self).setUp()
        self.assistant_client = self.get_assistant_client()

        self.assertEqual(StrictlyComment.objects.create(
            author = User.objects.get(username='******'),
            text = 'Hello, my assistant'
        ).pk,1)

        self.assertEqual(StrictlyComment.objects.create(
            author = User.objects.get(username='******'),
            text = 'Hi, oduvan'
        ).pk,2)

        self.assertEqual(Vote.get_votes_range(
            obj = StrictlyComment.objects.get(id=2),
            user = User.objects.get(username='******')
        ), [-1, 0, 1])
Example #24
0
 def create(self, validated_data):
     print 'In create'        
     vote = Vote()
     vote.voter = validated_data.get('voter')
     vote.vote = validated_data.get('vote')
     vote.content_type = validated_data.get('content_type')
     vote.object_id = validated_data.get('object_id')
     
     #Get row from contentType which has content_type
     content_object = ContentType.objects.get_for_id(vote.content_type.id)
     
     vote.content_object = content_object.model_class().objects.get(id=vote.object_id)
                     
     """
     Record a user's vote on a given object. Only allows a given user
     to vote once, though that vote may be changed.
     
     A zero vote indicates that any existing vote should be removed.
     """
     if vote.vote not in (+1, 0, -1):
         raise ValueError('Invalid vote (must be +1/0/-1)')
     
     # First, try to fetch the instance of this row from DB
     # If that does not exist, then it is the first time we're creating it
     # If it does, then just update the previous one
     try:
         vote_obj = Vote.objects.get(voter=vote.voter, content_type=vote.content_type, object_id=vote.object_id)
         if vote == 0 and not ZERO_VOTES_ALLOWED:
             vote_obj.delete()
         else:
             vote_obj.vote = vote
             vote_obj.save()
             
     except ObjectDoesNotExist:
         #This is the first time we're creating it
         try:
             if not ZERO_VOTES_ALLOWED and vote == 0:
                 # This shouldn't be happening actually
                 return
             vote_obj = Vote.objects.create(voter=vote.voter, content_type=vote.content_type, object_id=vote.object_id, vote=vote.vote)                        
         except:
             print '{file}: something went wrong in creating a vote object at {line}'.format(file=str('__FILE__'), line=str('__LINE__'))
             raise ObjectDoesNotExist    
     
     return vote_obj
Example #25
0
def poll_detail(request, pk):
    """Jedno konkrétní hlasování"""
    ## Tahle funkce je složitější, protože zpracovává nejen dotazy na
    ## aktuální stav (GET), ale i požadavky na změnu stavu (POST) – u nás
    ## přidání nového záznamu.

    ## Nejdřív z databáze načteme hlasování zadané v adrese.
    ## Pokud neexistuje, vrátíme chybu 404 (stránka neexistuje).
    poll = get_object_or_404(Poll, pk=pk)
    ## Nastavíme proměnnou, do které dáme popis chyby, kdyby něco šlo špatně.
    error = ''
    ## A teď: Pokud chtěl uživatel změnit stav (POST), musíme mu zkusit
    ## vyhovět.
    if request.method == 'POST':
        ## S požadavkem POST by měly přijít informace z formuláře, které nám
        ## Django zpřístupní ve slovníku "request.POST".
        ## Očekáváme něco jako:
        ## {'title': 'Janča', 'opt-1': True, 'opt-3': True}
        ## t.j. 'title' obsahuje jméno, a 'opt-X', pokud ve slovníku je,
        ## znamená že uživatel hlasuje pro danou možnost.
        ## Vezměme si ze slovníku ono jméno.
        title = request.POST.get('title')
        ## Pak si naplníme seznam hlasů.
        option_values = []
        ## Pro každou možnost v tomto hlasování ...
        for option in poll.options.all():
            ## ... zjistíme, jestli je v POST datech příslušný záznam,
            if 'opt-{}'.format(option.pk) in request.POST:
                value = True
            else:
                value = False
            ## A seznam plníme dvojicemi (N-ticemi): (možnost, hodnota).
            ## ("append" bere jen jeden argument: append(a, b) by nefungovalo,
            ## závorky navíc znamenají, že metodě posíláme jednu dvojici.)
            option_values.append((option, value))

        ## Jméno musí být vyplněno ...
        if title:
            ## ... a jestli je, zapíšeme do databáze.
            ## ("with transaction.atomic" říká, že pokud se některý z příkazů
            ## v tomhle bloku nepovede, databáze zůstane netknutá.
            ## Je dobré to aspoň pro zápisy do databáze pooužívat.)
            with transaction.atomic():
                ## Vytvoříme nový záznam, a vložíme do databáze
                record = Record(poll=poll, title=title)
                record.save()
                ## A pro všechny dvojice (možnost, hodnota), které
                ## jsme si před chvílí připravili, vytvoříme a uložíme
                ## odpovídající hlas.
                for option, value in option_values:
                    vote = Vote(option=option, record=record, value=value)
                    vote.save()
            ## A potom řekneme prohlížeči, aby stránku načetl znova,
            ## tentokrát metodou GET.
            ## (To je proto, že kdyby uživatel stránku načtenou pomocí POST
            ## obnovil (F5), formulář by se odeslal znovu.)
            return redirect('poll_detail', pk=pk)
        else:
            ## Nebyla-li data správná, nastavíme chybovou hlášku.
            error = 'Musíš zadat jméno.'

            ## Formulář teď uživateli ukážeme znova, s chybovou hláškou,
            ## ale o údaje které vyplnil nepřijde – máme je v "option_values"
            ## a použijeme je při vytvéření stránky.
    else:
        ## Poslal-li uživatel požadavek GET, nastavíme si "option_values"
        ## na dvojice jako výše, jen budou všechny hlasy zatím prázdné.
        option_values = []
        for option in poll.options.all():
            option_values.append((option, False))

    ## Teď můžeme tvořit výslednou stránku. Napřed si pěkně připravíme
    ## informace pro šablonu...
    data = {
        'poll': poll,       ## Objekt "Hlasování" se všemi informacemi
        'error': error,     ## Případná chybová hláška

        ## Dvojice (možnost, hodnota) pro hlasovací formulář
        'option_values': option_values,
    }
    ## Informace předáme do šablony, a necháme Django vytvořit stránku.
    return render(request, 'voting/poll_detail.html', data)
Example #26
0
 def vote(self, ranks):
     for item_id in ranks:
         self.page.form.set("c" + item_id, ranks[item_id])
     self.page.form.submit()
     return Vote.get_by_key_name(self.contest.key().name() + "/" +
                                 str(self.user.user_id()))
Example #27
0
 def vote(self, ranks):
     for item_id in ranks:
         self.page.form.set("c" + item_id, ranks[item_id])
     self.page.form.submit()
     return Vote.get_by_key_name(self.contest.key().name() + "/" + str(self.user.user_id()))
Example #28
0
    response_data['questions'] = questions
    return HttpResponse(json.dumps(response_data), mimetype="application/json")

def submit_vote(request):
    try:
        area = int(request.REQUEST['area'])
        q1 = int(request.REQUEST['question1'])
        q2 = int(request.REQUEST['question2'])
    except Exception, exc:
        logger.debug(exc)
        return HttpResponse(json.dumps({"error": 1, "msg": "There is an error on submitting your vote!"}), mimetype="application/json")
    
    logger.debug("%s, %s , %s" % (area, q1, q2))
    c = Choice.objects.get(pk=q1)
    a = Area.objects.get(pk=area)
    v = Vote(choice=c, area=a)
    v.save()
    
    c = Choice.objects.get(pk=q2)
    v = Vote(choice=c, area=a)
    v.save()
    
    yes = len(Vote.objects.select_related().filter(choice__choice_text='Yes'))
    no = len(Vote.objects.select_related().filter(choice__choice_text='No'))
    
    cursor = connection.cursor()
    cursor.execute('select count(*) as n, b.choice_text from voting_vote a, voting_choice b, voting_poll c where a.choice_id=b.id and b.poll_id=c.id and c.id=2 group by b.choice_text')
    total_rows = cursor.fetchall()
    logger.debug(total_rows)
    
    results = {"question1": [{"category": "yes", "answers": yes}, {"category": "no", "answers": no}], "question2" : total_rows}