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,)))
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
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()
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")
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())
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,)))
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)
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")
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)
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)
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)
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()
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)
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}