Skip to content

Commit

Permalink
Added the initial version of PollForm.
Browse files Browse the repository at this point in the history
  • Loading branch information
toastdriven committed Apr 16, 2011
1 parent 7ea5e1d commit 7d1d5e2
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 22 deletions.
17 changes: 17 additions & 0 deletions polls/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django import forms
from polls.models import Choice


class PollForm(forms.Form):
def __init__(self, *args, **kwargs):
# We require an ``instance`` parameter.
self.instance = kwargs.pop('instance')

# We call ``super`` (without the ``instance`` param) to finish
# off the setup.
super(PollForm, self).__init__(*args, **kwargs)

# We add on a ``choice`` field based on the instance we've got.
# This has to be done here (instead of declaratively) because the
# ``Poll`` instance will change from request to request.
self.fields['choice'] = forms.ModelChoiceField(queryset=Choice.objects.filter(poll=self.instance.pk), empty_label=None, widget=forms.RadioSelect)
6 changes: 3 additions & 3 deletions polls/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,14 @@ def test_bad_votes(self):
# Send no POST data.
resp = self.client.post(reverse('polls_vote', kwargs={'poll_id': 1}))
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.context['error_message'], "You didn't select a choice.")
self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.'])

# Send junk POST data.
resp = self.client.post(reverse('polls_vote', kwargs={'poll_id': 1}), {'foo': 'bar'})
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.context['error_message'], "You didn't select a choice.")
self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.'])

# Send a non-existant Choice PK.
resp = self.client.post(reverse('polls_vote', kwargs={'poll_id': 1}), {'choice': 300})
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.context['error_message'], "You didn't select a choice.")
self.assertEqual(resp.context['form']['choice'].errors, [u'Select a valid choice. That choice is not one of the available choices.'])
33 changes: 18 additions & 15 deletions polls/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from polls.forms import PollForm
from polls.models import Poll, Choice


Expand All @@ -12,7 +13,8 @@ def index(request):

def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
form = PollForm(instance=p)
return render_to_response('polls/detail.html', {'poll': p, 'form': form},
context_instance=RequestContext(request))


Expand All @@ -24,18 +26,19 @@ def results(request, poll_id):
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)

try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
if request.method == 'POST':
form = PollForm(request.POST, instance=p)

if form.is_valid():
choice = form.cleaned_data['choice']
choice.votes += 1
choice.save()

return HttpResponseRedirect(reverse('polls_results', kwargs={'poll_id': p.id}))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls_results', kwargs={'poll_id': p.id}))
form = PollForm(instance=p)

return render_to_response('polls/detail.html', {
'poll': p,
'form': form,
}, context_instance=RequestContext(request))
5 changes: 1 addition & 4 deletions templates/polls/detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ <h1>{{ poll.question }}</h1>

<form action="{% url polls_vote poll_id=poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
{{ form.as_p }}
<input type="submit" value="Vote" />
</form>

0 comments on commit 7d1d5e2

Please sign in to comment.