1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.db import models
5 from django.utils.translation import ugettext_lazy as _
6 from django.core.exceptions import ValidationError
7 from django.urls import reverse
10 USED_POLLS_KEY = 'used_polls'
13 class Poll(models.Model):
15 question = models.TextField(_('question'))
16 slug = models.SlugField(_('slug'))
17 open = models.BooleanField(_('open'), default=False)
20 verbose_name = _('Poll')
21 verbose_name_plural = _('Polls')
24 if self.open and Poll.objects.exclude(pk=self.pk).filter(slug=self.slug).exists():
25 raise ValidationError(_('Slug of an open poll needs to be unique'))
26 return super(Poll, self).clean()
29 return self.question[:100] + ' (' + self.slug + ')'
31 def get_absolute_url(self):
32 return reverse('poll', args=[self.slug])
36 return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
38 def voted(self, session):
39 return self.id in session.get(USED_POLLS_KEY, [])
42 class PollItem(models.Model):
44 poll = models.ForeignKey(Poll, models.CASCADE, related_name='items')
45 content = models.TextField(_('content'))
46 vote_count = models.IntegerField(_('vote count'), default=0)
49 verbose_name = _('vote item')
50 verbose_name_plural = _('vote items')
53 return self.content + ' @ ' + str(self.poll)
57 return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
59 def vote(self, session):
62 session.setdefault(USED_POLLS_KEY, []).append(self.poll.id)