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_vote(request, poll_slug): poll = get_object_or_404(Poll, slug=poll_slug) form = PollVoteForm(request.POST, request=request, poll=poll) if form.is_valid(): form.save() else: messages.success( request, "Please select an option before voting." ) return redirect(reverse("home"))
def poll_vote(request, poll_id, template): poll = get_object_or_404(Poll, id=poll_id) if request.method == 'POST': form = PollVoteForm(request.POST, request=request, poll=poll) if form.is_valid(): form.save() msg = _("Your vote has been saved") messages.success(request, msg, fail_silently=True) # If we're posting from a widget but the post is not by ajax then # we have to switch to the detail template. if (template == 'poll/poll_widget.html') and not request.is_ajax(): template = 'poll/poll_detail.html' else: form = PollVoteForm(request=request, poll=poll) extra = dict(form=form, object=poll, view_modifier=None) return render_to_response(template, extra, context_instance=RequestContext(request))
def poll_detail(context, obj): can_vote_on_poll, reason = obj.can_vote_on_poll(context['request']) context.update({ 'object': obj, 'can_vote_on_poll': can_vote_on_poll, 'reason': reason }) if can_vote_on_poll and not context.has_key('form'): context['form'] = PollVoteForm(request=context['request'], poll=obj) return context