diff gpp/polls/forms.py @ 439:1f139de929c4

Fixing #216; added anti-ballot stuffing feature to the polls application.
author Brian Neal <bgneal@gmail.com>
date Sat, 21 May 2011 19:55:48 +0000
parents dbd703f7d63a
children
line wrap: on
line diff
--- a/gpp/polls/forms.py	Wed May 18 03:04:25 2011 +0000
+++ b/gpp/polls/forms.py	Sat May 21 19:55:48 2011 +0000
@@ -1,16 +1,28 @@
 """Forms for the Polls application."""
 
 from django import forms
+from django.db.models import F
 
 from polls.models import Choice
 
 
 class VoteForm(forms.Form):
-   """Form for voting in a poll."""
-   choices = forms.ModelChoiceField(label='', empty_label=None,
-         queryset=Choice.objects.none(), widget=forms.RadioSelect)
+    """Form for voting in a poll."""
+    choices = forms.ModelChoiceField(label='', empty_label=None,
+            queryset=Choice.objects.none(), widget=forms.RadioSelect)
 
-   def __init__(self, poll, *args, **kwargs):
-      super(VoteForm, self).__init__(*args, **kwargs)
-      self.fields['choices'].queryset = poll.choice_set.all()
+    def __init__(self, poll, *args, **kwargs):
+        self.user = kwargs.pop('user', None)
+        self.user_choice = kwargs.pop('user_choice', None)
+        super(VoteForm, self).__init__(*args, **kwargs)
+        self.fields['choices'].queryset = poll.choice_set.all()
 
+    def clean(self):
+        if self.user_choice:
+            raise forms.ValidationError("You've already voted in this poll!")
+        return self.cleaned_data
+
+    def save(self):
+        choice = self.cleaned_data['choices']
+        Choice.objects.filter(id=choice.id).update(votes=F('votes') + 1)
+        choice.voters.add(self.user)