Submission string representation in admin
[edumed.git] / wtem / models.py
1 import random
2 import string
3
4 from django.db import models
5 from django.contrib.auth.models import User
6 from django.core.exceptions import ValidationError
7 from django.utils.translation import ugettext as _
8 from jsonfield import JSONField
9
10 from contact.models import Contact
11
12
13 DEBUG_KEY = '12345'
14
15 class Submission(models.Model):
16     contact = models.ForeignKey(Contact, null = True)
17     key = models.CharField(max_length = 30, unique = True)
18     first_name = models.CharField(max_length = 100)
19     last_name = models.CharField(max_length = 100)
20     email = models.EmailField(max_length = 100, unique = True)
21     answers = models.CharField(max_length = 65536, null = True, blank = True)
22     key_sent = models.BooleanField(default = False)
23     def __unicode__(self):
24         return ', '.join((self.last_name, self.first_name, self.email))
25
26     @classmethod
27     def generate_key(cls):
28         key = ''
29         while not key or key in [record['key'] for record in cls.objects.values('key')]:
30             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
31         return key
32
33     @classmethod
34     def create(cls, first_name, last_name, email, key = None, contact = None):
35         submission = cls(
36             contact = contact,
37             key = key if key else Submission.generate_key(),
38             first_name = first_name,
39             last_name = last_name,
40             email = email
41         )
42
43         submission.save()
44         return submission
45
46
47 class Attachment(models.Model):
48     submission = models.ForeignKey(Submission)
49     name = models.CharField(max_length=100)
50     file = models.FileField(upload_to = 'wtem/attachment')
51
52
53 class Assignment(models.Model):
54     user = models.ForeignKey(User, unique = True)
55     exercises = JSONField()
56
57     def clean(self):
58         if not isinstance(self.exercises, list):
59             raise ValidationError(_('Assigned exercises must be declared in a list format'))
60         for exercise in self.exercises:
61             if not isinstance(exercise, int) or exercise < 1:
62                 raise ValidationError(_('Invalid exercise id: %s' % exercise))
63
64     def __unicode__(self):
65         return self.user.username + ': ' + ','.join(map(str,self.exercises))