models.py 3.89 KB
Newer Older
Christophe Siraut's avatar
Christophe Siraut committed
1
from django.db import models
2
from django.contrib.auth.models import User
3
from django.contrib.sites.models import Site
Christophe Siraut's avatar
Christophe Siraut committed
4 5
from django.contrib.auth.signals import user_logged_in
from django.core.exceptions import ObjectDoesNotExist
6
from django.core.urlresolvers import reverse
7
from django.utils.translation import ugettext_lazy as _
Christophe Siraut's avatar
Christophe Siraut committed
8
import datetime
9 10
import string
import random
11
import jsonfield
12 13 14 15 16 17 18

def createId(length):
    firstchar = string.ascii_letters
    c = string.digits + string.ascii_letters
    lastchars = ''.join([random.choice(c) for dummy in xrange(0, length - 1)])
    return random.choice(firstchar) + lastchars

chris's avatar
chris committed
19

Christophe Siraut's avatar
Christophe Siraut committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33
def login_handler(user, **kwargs):
    """Verify user profile exists"""
    try:
        profile = UserProfile.objects.get(user=user)
    except ObjectDoesNotExist:
        profile = UserProfile(user=user)
        profile.save()
    return

user_logged_in.connect(login_handler)


class UserProfile(models.Model):
    user = models.OneToOneField(User)
34
    email_notifications = models.BooleanField(default=False)
Christophe Siraut's avatar
Christophe Siraut committed
35

36

chris's avatar
chris committed
37
class Poll(models.Model):
38 39 40 41 42
    # Override django id AutoField with randomly generated hash
    id = models.CharField(
        primary_key=True,
        max_length=8,
        default=createId(5))
Christophe Siraut's avatar
Christophe Siraut committed
43
    title = models.CharField(_('Title'), max_length=80)
Christophe Siraut's avatar
Christophe Siraut committed
44
    pub_date = models.DateField(default=datetime.datetime.now)
45 46
    upd_date = models.DateField(auto_now=True)
    description = models.CharField(max_length=300)
47
    user = models.ForeignKey(User, null=True)
48 49
    result = jsonfield.JSONField()

chris's avatar
chris committed
50 51 52 53
    def save(self, *args, **kwargs):
        self.compile()
        super(Poll, self).save(*args, **kwargs)

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    def compile(self):
        self.result = {'voters': self.compile_voters(),
                       'choices': self.compile_choices()}

    def compile_voters(self):
        '''Return a list of votes by voter'''
        voters = []
        for b in self.bulletin_set.all():
            say = []
            for c in self.choice_set.all():
                try:
                    v = b.vote_set.get(choice=c)
                    say.append((v.voice, v.comment))
                except:
                    say.append((None, None))
            voters.append({b.voter: say})
        return voters

    def compile_choices(self):
        '''Return a list of choices'''
        choices = []
        for c in self.choice_set.all():
            t = 0
            l = []
            for v in c.vote_set.filter(choice=c):
                if v.voice:
                    t += 1
                if v.comment:
                    l.append([v.bulletin.voter, v.comment])
            choices.append((c.choice, c.details, t, l))
        return choices
chris's avatar
chris committed
85 86 87 88

    def __unicode__(self):
        return self.title

89 90
    @property
    def link(self):
91 92 93
        return 'http://%s%s' % (
            Site.objects.get_current(),
            reverse('meetingpoll', args=(self.id,)))
94

95

chris's avatar
chris committed
96 97
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
98
    choice = models.DateTimeField()
Christophe Siraut's avatar
Christophe Siraut committed
99 100
    details = models.CharField(max_length=200, blank=True)
    votecount = models.IntegerField(default=0, blank=True)
101

102 103
    class Meta:
        ordering = ['choice']
104

chris's avatar
chris committed
105
    def __unicode__(self):
106 107
        return str(self.choice)

chris's avatar
chris committed
108

chris's avatar
chris committed
109
class Bulletin(models.Model):
Christophe Siraut's avatar
Christophe Siraut committed
110 111
    poll = models.ForeignKey(Poll, editable=False)
    voter = models.CharField("", max_length=40)
chris's avatar
chris committed
112 113 114 115

    def __unicode__(self):
        return self.voter

chris's avatar
chris committed
116 117 118 119 120 121
        if not Bulletin.objects.filter(poll=poll.id, voter=voter):
            bulletin = Bulletin(poll=poll, voter=voter)
            bulletin.save()
        else:
            bulletin = Bulletin.objects.get(poll=poll.id, voter=voter)
        return bulletin
122

chris's avatar
chris committed
123 124 125
class Vote(models.Model):
    choice = models.ForeignKey(Choice)
    bulletin = models.ForeignKey(Bulletin)
126
    voice = models.BooleanField(default=False)
Christophe Siraut's avatar
Christophe Siraut committed
127
    comment = models.CharField(max_length=80, blank=True)
128

129 130
    class Meta:
        ordering = ['choice']
131

chris's avatar
chris committed
132
    def __unicode__(self):
chris's avatar
chris committed
133
        return str(self.voice)