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 poll(request, poll_id): if request.method == 'POST': choice = Choice.objects.get(id=request.POST['vote']) choice.votes += 1 choice.save() return HttpResponseRedirect(reverse('poll', args=[ poll_id, ])) poll = Poll.objects.get(pk=poll_id) form = PollVoteForm(poll=poll) return render(request, 'polls/poll.html', {'poll': poll, 'form': form})