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
10 from contact.models import Contact
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)
25 def __unicode__(self):
26 return ', '.join((self.last_name, self.first_name, self.email))
29 def generate_key(cls):
31 while not key or key in [record['key'] for record in cls.objects.values('key')]:
32 key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
36 def create(cls, first_name, last_name, email, key = None, contact = None):
39 key = key if key else Submission.generate_key(),
40 first_name = first_name,
41 last_name = last_name,
48 def get_mark(self, user_id, exercise_id):
50 user_id = str(user_id)
51 exercise_id = str(exercise_id)
52 if self.marks and user_id in self.marks:
53 mark = self.marks[user_id].get(exercise_id, None)
56 def set_mark(self, user_id, exercise_id, mark):
57 user_id = str(user_id)
58 exercise_id = str(exercise_id)
62 self.marks.setdefault(user_id, {})[exercise_id] = mark
64 del self.marks[user_id][exercise_id]
67 class Attachment(models.Model):
68 submission = models.ForeignKey(Submission)
69 name = models.CharField(max_length=100)
70 file = models.FileField(upload_to = 'wtem/attachment')
73 class Assignment(models.Model):
74 user = models.ForeignKey(User, unique = True)
75 exercises = JSONField()
78 if not isinstance(self.exercises, list):
79 raise ValidationError(_('Assigned exercises must be declared in a list format'))
80 for exercise in self.exercises:
81 if not isinstance(exercise, int) or exercise < 1:
82 raise ValidationError(_('Invalid exercise id: %s' % exercise))
84 def __unicode__(self):
85 return self.user.username + ': ' + ','.join(map(str,self.exercises))