pep8 and other code-style changes
[wolnelektury.git] / src / polls / models.py
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.
4 #
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
9
10
11 USED_POLLS_KEY = 'used_polls'
12
13
14 class Poll(models.Model):
15
16     question = models.TextField(_('question'))
17     slug = models.SlugField(_('slug'))
18     open = models.BooleanField(_('open'), default=False)
19
20     class Meta:
21         verbose_name = _('Poll')
22         verbose_name_plural = _('Polls')
23
24     def clean(self):
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()
28
29     def __unicode__(self):
30         return self.question[:100] + ' (' + self.slug + ')'
31
32     def get_absolute_url(self):
33         return reverse('poll', args=[self.slug])
34
35     @property
36     def vote_count(self):
37         return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
38
39     def voted(self, session):
40         return self.id in session.get(USED_POLLS_KEY, [])
41
42
43 class PollItem(models.Model):
44
45     poll = models.ForeignKey(Poll, related_name='items')
46     content = models.TextField(_('content'))
47     vote_count = models.IntegerField(_('vote count'), default=0)
48
49     class Meta:
50         verbose_name = _('vote item')
51         verbose_name_plural = _('vote items')
52
53     def __unicode__(self):
54         return self.content + ' @ ' + unicode(self.poll)
55
56     @property
57     def vote_ratio(self):
58         return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
59
60     def vote(self, session):
61         self.vote_count += 1
62         self.save()
63         session.setdefault(USED_POLLS_KEY, []).append(self.poll.id)
64         session.save()