def seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite = False): """ Seeds num_entries poll with random users as owners Each poll will be seeded with # choices from choice_min to choice_max """ if overwrite: print("over writing poll") Poll.objects.all().delete() users = list(User.objects.all()) count = 0 for _ in range(num_entries): p = Poll( owner = random.choice(users), text=fake.paragraph(), pub_date=datetime.datetime.now() ) p.save() num_choices = random.randrange(choice_min,choice_max+1) for _ in range(num_choices): c = Choice( poll=p, choice_text=fake.sentence() ) c.save() count += 1 perecent_complete = count / num_entries * 100 print( "Addind {} new poll: {:.2f}%".format( num_entries, perecent_complete ), end='\r', flush=True ) print()
def test_form_renders_poll_choices_as_radio_inputs(self): # set up a poll with a couple of choices poll1 = Poll(question="6 times 7", pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice="42", votes=0) choice1.save() choice2 = Choice(poll=poll1, choice="The Ultimate Answer", votes=0) choice2.save() # set up another poll to make sure we only see the right choices poll2 = Poll(question="time", pub_date=timezone.now()) poll2.save() choice3 = Choice(poll=poll2, choice="PM", votes=0) choice3.save() # build a voting form for poll1 form = PollVoteForm(poll=poll1) # check it has a single field called 'vote', which has right choices: self.assertEquals(form.fields.keys(), ["vote"]) # choices are tuples in the format (choice_number, choice_text): self.assertEquals(form.fields["vote"].choices, [(choice1.id, choice1.choice), (choice2.id, choice2.choice)]) # check it uses radio inputs to render self.assertIn('input type="radio"', form.as_p())
def setup_choices(self, question): choice1 = Choice(code="a", question=question, text="a") choice2 = Choice(code="b", question=question, text="a") choice3 = Choice(code="c", question=question, text="a") choice1.save() choice2.save() choice3.save()
def setup_choices(self,question): choice1 = Choice(code= 'a',question=question, text="a") choice2 = Choice(code= 'b',question=question, text="a") choice3 = Choice(code= 'c',question=question, text="a") choice1.save() choice2.save() choice3.save()
def create_new_choice_for_poll_from_post_data(cls, poll, post_data): choice = Choice.create( choice=post_data['choice'], poll=poll ) return choice
def poll(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choices = Choice.get_choices_for_poll(poll) return views.view_poll(poll, choices)
def poll(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choices = Choice.get_choices_for_poll(poll) #csrf_token = generate_csrf() return views.view_poll(poll, choices, csrf_token=None)
def cast_vote_from_post_data(cls, poll_id, post_data): choice = Choice.get(Choice.poll_id == poll_id, Choice.id == post_data['choice_id']) redis_cache.delete("poll-total-votes-{0}".format(poll_id)) redis_cache.delete("choice-total-votes-{0}".format(choice.id)) vote = VoteCast.create(poll=choice.poll, choice=choice) return vote
def cast_vote_from_post_data(cls, poll_id, post_data): choice = Choice.get(Choice.poll_id == poll_id, Choice.id == post_data['choice_id']) vote = VoteCast.create( poll=choice.poll, choice=choice ) return vote
def get(self,request,id=None): if id: pass else: poll_form = PollForm(instance=Questions()) choice_forms = [ChoiceForm(prefix=str( x), instance=Choice()) for x in range(3)] context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'poll/new_poll.html', context)
def test_view_can_handle_votes_via_POST(self): # set up a poll with choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=1) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=3) choice2.save() # set up our POST data - keys and values are strings post_data = {'vote': str(choice2.id)} # make our request to the view poll_url = '/poll/polls/%d/' % (poll1.id,) response = self.client.post(poll_url, data=post_data) # retrieve the updated choice from the database choice_in_db = Choice.objects.get(pk=choice2.id) # check it's votes have gone up by 1 self.assertEquals(choice_in_db.votes, 4) self.assertEquals(choice_in_db.percentage(), 80) # always redirect after a POST - even if, in this case, we go back # to the same page. self.assertRedirects(response, poll_url)
def poll_vote(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choice_id = request.form['choice_id'] choice = Choice.get_by_id_for_poll(poll, choice_id) if not choice: return abort(404) choice.cast_vote() return redirect(url_for('poll', poll_id=poll.id))
def add_poll(request): if request.method == "POST": form = PollForm(request.POST) if form.is_valid(): new_poll = form.save(commit=False) new_poll.owner = request.user new_poll.save() new_choice1 = Choice( poll=new_poll, choice_text=form.cleaned_data['choice1']).save() new_choice2 = Choice( poll=new_poll, choice_text=form.cleaned_data['choice2']).save() messages.success( request, "Poll and Choices added successfully", extra_tags='alert alert-success alert-dismissible fade show') return redirect('poll:polls') else: form = PollForm() context = {'form': form} return render(request, 'poll/add_poll.html', context)
def get(self, request, id=None): if id: question = get_object_or_404(Qustions, id = id) poll_form = PollForm(instance=question) choices = question.choice_set.all() choice_forms = [ChoiceForm(prefix=str( choice.id), instance=choice) for choice in choice in choices ] template = 'polls/edit_poll.html' else: poll_form = PollForm(instance=Questions()) choice_forms = [ChoiceForm(prefix=str( x), instance=Choice()) for x in range(3)] template = 'polls/new_poll.html' context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, template, context)
def post(self, request, id=None): context = {} if id: return self.put(request, id) poll_form = PollForm(request.POST, instance=Questions()) choice_forms = [ChoiceForm(request.POST, prefix=str( x), instance=Choice()) for x in range(0, 3)] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_forms]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_forms: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return HttpResponseRedirect('/poll/') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/new_poll.html', context)
def convert_poll_choices(self): cursor = connection.cursor() cursor.execute("SELECT * FROM smf_poll_choices") rows = cursor.fetchall() for row in rows: try: poll = Poll.objects.get(old_poll_id=row[0]) try: choice = Choice() choice.poll = poll choice.old_choice_id = row[1] choice.label = row[2] choice.votes = row[3] choice.save() except Exception, e: print str(e) except Poll.DoesNotExist, e: print str(e)
def test_get_number_of_votes(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() assert p.number_of_votes() == 0 c1 = Choice(id=None, choice="Premier choix", poll=p) c1.save() c2 = Choice(id=None, choice="Deuxième choix", poll=p) c2.save() assert p.number_of_votes() == 0 VoteCast.create(poll=p, choice=c1) VoteCast.create(poll=p, choice=c1) VoteCast.create(poll=p, choice=c2) assert p.number_of_votes() == 3
def convert_poll_choices(self): cursor = connection.cursor(); cursor.execute("SELECT * FROM smf_poll_choices"); rows = cursor.fetchall() for row in rows: try: poll = Poll.objects.get(old_poll_id=row[0]) try: choice = Choice() choice.poll = poll choice.old_choice_id = row[1] choice.label = row[2] choice.votes = row[3] choice.save() except Exception, e: print str(e) except Poll.DoesNotExist, e: print str(e)
def test_page_shows_choices_using_form(self): # set up a poll with choices poll1 = Poll(question='time', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice="PM", votes=0) choice1.save() choice2 = Choice(poll=poll1, choice="Gardener's", votes=0) choice2.save() response = self.client.get('/poll/polls/%d/' % (poll1.id, )) # check we've passed in a form of the right type self.assertTrue(isinstance(response.context['form'], PollVoteForm)) self.assertTrue(response.context['poll'], poll1) self.assertTemplateUsed(response, 'poll.html') # and check the check the form is being used in the template, # by checking for the choice text self.assertIn(choice1.choice, response.content.replace(''', "'")) self.assertIn(choice2.choice, response.content.replace(''', "'")) self.assertIn('csrf', response.content) self.assertIn('0 %', response.content)
def create_new_choice_for_poll_from_post_data(cls, poll, post_data): choice = Choice(id=None, choice=post_data['choice'], poll=poll) choice.save() return choice