gremmie@1: """Forms for the Polls application.""" gremmie@1: gremmie@1: from django import forms bgneal@439: from django.db.models import F gremmie@1: gremmie@1: from polls.models import Choice gremmie@1: gremmie@1: gremmie@1: class VoteForm(forms.Form): bgneal@439: """Form for voting in a poll.""" bgneal@439: choices = forms.ModelChoiceField(label='', empty_label=None, bgneal@439: queryset=Choice.objects.none(), widget=forms.RadioSelect) gremmie@1: bgneal@439: def __init__(self, poll, *args, **kwargs): bgneal@439: self.user = kwargs.pop('user', None) bgneal@439: self.user_choice = kwargs.pop('user_choice', None) bgneal@439: super(VoteForm, self).__init__(*args, **kwargs) bgneal@439: self.fields['choices'].queryset = poll.choice_set.all() gremmie@1: bgneal@439: def clean(self): bgneal@439: if self.user_choice: bgneal@439: raise forms.ValidationError("You've already voted in this poll!") bgneal@439: return self.cleaned_data bgneal@439: bgneal@439: def save(self): bgneal@439: choice = self.cleaned_data['choices'] bgneal@439: Choice.objects.filter(id=choice.id).update(votes=F('votes') + 1) bgneal@439: choice.voters.add(self.user)