1 from django.db import models
2 from django.utils.translation import ugettext_lazy as _
3 from django.core.exceptions import ValidationError
4 from django.core.urlresolvers import reverse
7 USED_POLLS_KEY = 'used_polls'
10 class Poll(models.Model):
12 question = models.TextField(_('question'))
13 slug = models.SlugField(_('slug'))
14 open = models.BooleanField(_('open'), default = False)
17 verbose_name = _('Poll')
18 verbose_name_plural = _('Polls')
21 if self.open and Poll.objects.exclude(pk = self.pk).filter(slug = self.slug).exists():
22 raise ValidationError(_('Slug of an open poll needs to be unique'))
23 return super(Poll, self).clean()
25 def __unicode__(self):
26 return self.question[:100] + ' (' + self.slug + ')'
28 def get_absolute_url(self):
29 return reverse('poll', args = [self.slug])
33 return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
35 def voted(self, session):
36 return self.id in session.get(USED_POLLS_KEY, set())
39 class PollItem(models.Model):
41 poll = models.ForeignKey(Poll, related_name = 'items')
42 content = models.TextField(_('content'))
43 vote_count = models.IntegerField(_('vote count'), default = 0)
46 verbose_name = _('vote item')
47 verbose_name_plural = _('vote items')
49 def __unicode__(self):
50 return self.content + ' @ ' + unicode(self.poll)
54 return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
56 def vote(self, session):
57 self.vote_count = self.vote_count + 1
59 session.setdefault(USED_POLLS_KEY, set()).add(self.poll.id)