1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from django.db import models
5 from django.core.exceptions import ValidationError
6 from django.urls import reverse
9 USED_POLLS_KEY = 'used_polls'
12 class Poll(models.Model):
14 question = models.TextField('pytanie')
15 slug = models.SlugField('slug')
16 open = models.BooleanField('otwarta', default=False)
19 verbose_name = 'ankieta'
20 verbose_name_plural = 'ankiety'
23 if self.open and Poll.objects.exclude(pk=self.pk).filter(slug=self.slug).exists():
24 raise ValidationError('Slug otwartej ankiety musi być unikalny')
25 return super(Poll, self).clean()
28 return self.question[:100] + ' (' + self.slug + ')'
30 def get_absolute_url(self):
31 return reverse('poll', args=[self.slug])
35 return self.items.all().aggregate(models.Sum('vote_count'))['vote_count__sum']
37 def voted(self, session):
38 return self.id in session.get(USED_POLLS_KEY, [])
41 class PollItem(models.Model):
43 poll = models.ForeignKey(Poll, models.CASCADE, related_name='items')
44 content = models.TextField('treść')
45 vote_count = models.IntegerField('licznik głosów', default=0)
48 verbose_name = 'pozycja ankiety'
49 verbose_name_plural = 'pozycje ankiety'
52 return self.content + ' @ ' + str(self.poll)
56 return (float(self.vote_count) / self.poll.vote_count) * 100 if self.poll.vote_count else 0
58 def vote(self, session):
61 session.setdefault(USED_POLLS_KEY, []).append(self.poll.id)