1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.db import models
6 from django.utils.translation import ugettext_lazy as _
7 from django.core.exceptions import ValidationError
8 from django.core.urlresolvers import reverse
11 USED_POLLS_KEY = 'used_polls'
14 class Poll(models.Model):
16 question = models.TextField(_('question'))
17 slug = models.SlugField(_('slug'))
18 open = models.BooleanField(_('open'), default=False)
21 verbose_name = _('Poll')
22 verbose_name_plural = _('Polls')
25 if self.open and Poll.objects.exclude(pk=self.pk).filter(slug=self.slug).exists():
26 raise ValidationError(_('Slug of an open poll needs to be unique'))
27 return super(Poll, self).clean()
30 return self.question[:100] + ' (' + self.slug + ')'
32 def get_absolute_url(self):
33 return reverse('poll', args=[self.slug])
37 return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
39 def voted(self, session):
40 return self.id in session.get(USED_POLLS_KEY, [])
43 class PollItem(models.Model):
45 poll = models.ForeignKey(Poll, related_name='items')
46 content = models.TextField(_('content'))
47 vote_count = models.IntegerField(_('vote count'), default=0)
50 verbose_name = _('vote item')
51 verbose_name_plural = _('vote items')
54 return self.content + ' @ ' + str(self.poll)
58 return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
60 def vote(self, session):
63 session.setdefault(USED_POLLS_KEY, []).append(self.poll.id)