wip: saving submission with file attachments
[edumed.git] / wtem / models.py
1 import random
2 import string
3
4 from django.db import models
5
6 from contact.models import Contact
7
8
9 class Submission(models.Model):
10     contact = models.ForeignKey(Contact, null = True)
11     key = models.CharField(max_length = 30, unique = True)
12     first_name = models.CharField(max_length = 100)
13     last_name = models.CharField(max_length = 100)
14     email = models.EmailField(max_length = 100, unique = True)
15     answers = models.CharField(max_length = 65536, null = True, blank = True)
16
17     @classmethod
18     def generate_key(cls):
19         key = ''
20         while not key and key in [record['key'] for record in cls.objects.values('key')]:
21             key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for i in range(30))
22         return key
23
24     @classmethod
25     def create(cls, first_name, last_name, email, contact = None, key = None):
26         submissions = []
27
28         if contact:
29             students = contact['students']
30         else:
31             students = [dict(first_name = first_name, last_name = last_name, email = email)]
32         
33         if key is None:
34             key = Submission.generate_key()
35
36         for student in students:
37             submission = cls(
38                 contact = contact,
39                 key = key,
40                 first_name = student['first_name'],
41                 last_name = student['last_name'],
42                 email = student['email']
43             )
44             submission.save()
45             submissions.append(submission)
46         return submissions
47
48
49 class Attachment(models.Model):
50     submission = models.ForeignKey(Submission)
51     name = models.CharField(max_length=100)
52     file = models.FileField(upload_to = 'wtem/attachment')