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())
19 DEBUG_KEY = 'smerfetka159'
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 statement[1] == 'ignore':
132 if answer[idx] == 'true':
134 elif answer[idx] == 'false':
138 if given == statement[1]:
139 toret += exercise['points_per_hit']
141 raise NotImplementedError
144 def final_result(self):
146 # for exercise_id in map(str,range(1, len(exercises) + 1)):
147 for exercise_id in [str(x['id']) for x in exercises]:
148 mark = self.get_final_exercise_mark(exercise_id)
154 def final_result_as_string(self):
155 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
158 class Attachment(models.Model):
159 submission = models.ForeignKey(Submission)
160 exercise_id = models.IntegerField()
161 tag = models.CharField(max_length=128, null=True, blank=True)
162 file = models.FileField(upload_to='wtem/attachment')
165 class Assignment(models.Model):
166 user = models.ForeignKey(User, unique=True)
167 exercises = JSONField()
170 if not isinstance(self.exercises, list):
171 raise ValidationError(_('Assigned exercises must be declared in a list format'))
172 # for exercise in self.exercises:
173 # if not isinstance(exercise, int) or exercise < 1:
174 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
176 def __unicode__(self):
177 return self.user.username + ': ' + ','.join(map(str, self.exercises))
180 def exercise_checked_manually(exercise):
181 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise