annotate polls/forms.py @ 917:0365fdbb4d78

Fix app conflict with messages. Django's messages app label conflicts with our messages app. We can't easily rename our label as that will make us rename database tables. Since our app came first we'll just customize Django messages label. For Django 1.7.7 upgrade.
author Brian Neal <bgneal@gmail.com>
date Mon, 06 Apr 2015 20:02:25 -0500
parents ee87ea74d46b
children
rev   line source
gremmie@1 1 """Forms for the Polls application."""
gremmie@1 2
gremmie@1 3 from django import forms
bgneal@439 4 from django.db.models import F
gremmie@1 5
gremmie@1 6 from polls.models import Choice
gremmie@1 7
gremmie@1 8
gremmie@1 9 class VoteForm(forms.Form):
bgneal@439 10 """Form for voting in a poll."""
bgneal@439 11 choices = forms.ModelChoiceField(label='', empty_label=None,
bgneal@439 12 queryset=Choice.objects.none(), widget=forms.RadioSelect)
gremmie@1 13
bgneal@439 14 def __init__(self, poll, *args, **kwargs):
bgneal@439 15 self.user = kwargs.pop('user', None)
bgneal@439 16 self.user_choice = kwargs.pop('user_choice', None)
bgneal@439 17 super(VoteForm, self).__init__(*args, **kwargs)
bgneal@439 18 self.fields['choices'].queryset = poll.choice_set.all()
gremmie@1 19
bgneal@439 20 def clean(self):
bgneal@439 21 if self.user_choice:
bgneal@439 22 raise forms.ValidationError("You've already voted in this poll!")
bgneal@439 23 return self.cleaned_data
bgneal@439 24
bgneal@439 25 def save(self):
bgneal@439 26 choice = self.cleaned_data['choices']
bgneal@439 27 Choice.objects.filter(id=choice.id).update(votes=F('votes') + 1)
bgneal@439 28 choice.voters.add(self.user)