1 # -*- coding: utf-8 -*-
7 from django.db import models
8 from django.contrib.auth.models import User
9 from django.core.exceptions import ValidationError
10 from django.utils.translation import ugettext as _
11 from jsonfield import JSONField
13 from contact.models import Contact
15 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
16 exercises = json.loads(f.read())
22 class Submission(models.Model):
23 contact = models.ForeignKey(Contact, null=True)
24 key = models.CharField(max_length=30, unique=True)
25 first_name = models.CharField(max_length=100)
26 last_name = models.CharField(max_length=100)
27 email = models.EmailField(max_length=100, unique=True)
28 answers = models.CharField(max_length=65536, null=True, blank=True)
29 key_sent = models.BooleanField(default=False)
30 marks = JSONField(default={})
31 examiners = models.ManyToManyField(User, null=True, blank=True)
32 end_time = models.CharField(max_length=5, null=True, blank=True)
34 def __unicode__(self):
35 return ', '.join((self.last_name, self.first_name, self.email))
38 def generate_key(cls):
40 while not key or key in [record['key'] for record in cls.objects.values('key')]:
41 key = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
46 def create(cls, first_name, last_name, email, key=None, contact=None):
49 key=key if key else Submission.generate_key(),
50 first_name=first_name,
58 def get_mark(self, user_id, exercise_id):
60 user_id = str(user_id)
61 exercise_id = str(exercise_id)
62 if self.marks and user_id in self.marks:
63 mark = self.marks[user_id].get(exercise_id, None)
66 def set_mark(self, user_id, exercise_id, mark):
67 user_id = str(user_id)
68 exercise_id = str(exercise_id)
72 self.marks.setdefault(user_id, {})[exercise_id] = mark
74 del self.marks[user_id][exercise_id]
76 def get_exercise_marks_by_examiner(self, exercise_id):
78 for examiner_id, examiner_marks in self.marks.items():
79 mark = examiner_marks.get(exercise_id, None)
81 marks[examiner_id] = mark
84 def get_final_exercise_mark(self, exercise_id):
85 # exercise = exercises[int(exercise_id)-1]
86 exercise = [e for e in exercises if str(e['id']) == str(exercise_id)][0]
87 if exercise_checked_manually(exercise):
88 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
89 if len(marks_by_examiner):
90 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
96 answer = json.loads(self.answers)[exercise_id]['closed_part']
98 if t == 'edumed_uporzadkuj':
99 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
100 if t == 'edumed_przyporzadkuj':
102 for bucket_id, items in answer.items():
103 for item_id in items:
105 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
106 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
108 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
110 toret += exercise['points_per_hit']
112 if t == 'edumed_wybor':
113 if len(exercise['answer']) == 1:
114 if len(answer) and int(answer[0]) == exercise['answer'][0]:
115 return exercise['points']
120 if exercise.get('answer_mode', None) == 'all_or_nothing':
121 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
123 for answer_id in map(int, answer):
124 if answer_id in exercise['answer']:
125 toret += exercise['points_per_hit']
127 if t == 'edumed_prawdafalsz':
129 for idx, statement in enumerate(exercise['statements']):
130 if answer[idx] == 'true':
132 elif answer[idx] == 'false':
136 if given == statement[1]:
137 toret += exercise['points_per_hit']
139 raise NotImplementedError
142 def final_result(self):
144 # for exercise_id in map(str,range(1, len(exercises) + 1)):
145 for exercise_id in [str(x['id']) for x in exercises]:
146 mark = self.get_final_exercise_mark(exercise_id)
152 def final_result_as_string(self):
153 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
156 class Attachment(models.Model):
157 submission = models.ForeignKey(Submission)
158 exercise_id = models.IntegerField()
159 tag = models.CharField(max_length=128, null=True, blank=True)
160 file = models.FileField(upload_to='wtem/attachment')
163 class Assignment(models.Model):
164 user = models.ForeignKey(User, unique=True)
165 exercises = JSONField()
168 if not isinstance(self.exercises, list):
169 raise ValidationError(_('Assigned exercises must be declared in a list format'))
170 # for exercise in self.exercises:
171 # if not isinstance(exercise, int) or exercise < 1:
172 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
174 def __unicode__(self):
175 return self.user.username + ': ' + ','.join(map(str, self.exercises))
178 def exercise_checked_manually(exercise):
179 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise