Assignment string representation for 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
24     @classmethod
25     def generate_key(cls):
26         key = ''
27         while not key or key in [record['key'] for record in cls.objects.values('key')]:
28             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
29         return key
30
31     @classmethod
32     def create(cls, first_name, last_name, email, key = None, contact = None):
33         submission = cls(
34             contact = contact,
35             key = key if key else Submission.generate_key(),
36             first_name = first_name,
37             last_name = last_name,
38             email = email
39         )
40
41         submission.save()
42         return submission
43
44
45 class Attachment(models.Model):
46     submission = models.ForeignKey(Submission)
47     name = models.CharField(max_length=100)
48     file = models.FileField(upload_to = 'wtem/attachment')
49
50
51 class Assignment(models.Model):
52     user = models.ForeignKey(User, unique = True)
53     exercises = JSONField()
54
55     def clean(self):
56         if not isinstance(self.exercises, list):
57             raise ValidationError(_('Assigned exercises must be declared in a list format'))
58         for exercise in self.exercises:
59             if not isinstance(exercise, int) or exercise < 1:
60                 raise ValidationError(_('Invalid exercise id: %s' % exercise))
61
62     def __unicode__(self):
63         return self.user.username + ': ' + ','.join(map(str,self.exercises))