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.core.urlresolvers import reverse
11 from django.utils.translation import ugettext as _
12 from jsonfield import JSONField
14 from contact.models import Contact
16 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
17 exercises = json.loads(f.read())
20 DEBUG_KEY = 'smerfetka159'
25 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
26 for i in range(length))
29 class Submission(models.Model):
30 contact = models.ForeignKey(Contact, null=True)
31 key = models.CharField(max_length=30, unique=True)
32 first_name = models.CharField(max_length=100)
33 last_name = models.CharField(max_length=100)
34 email = models.EmailField(max_length=100, unique=True)
35 answers = models.CharField(max_length=65536, null=True, blank=True)
36 key_sent = models.BooleanField(default=False)
37 marks = JSONField(default={})
38 examiners = models.ManyToManyField(User, null=True, blank=True)
39 end_time = models.CharField(max_length=5, null=True, blank=True)
41 def __unicode__(self):
42 return ', '.join((self.last_name, self.first_name, self.email))
45 def generate_key(cls):
47 while not key or key in [record['key'] for record in cls.objects.values('key')]:
52 def create(cls, first_name, last_name, email, key=None, contact=None):
55 key=key if key else Submission.generate_key(),
56 first_name=first_name,
64 def get_mark(self, user_id, exercise_id):
66 user_id = str(user_id)
67 exercise_id = str(exercise_id)
68 if self.marks and user_id in self.marks:
69 mark = self.marks[user_id].get(exercise_id, None)
72 def set_mark(self, user_id, exercise_id, mark):
73 user_id = str(user_id)
74 exercise_id = str(exercise_id)
78 self.marks.setdefault(user_id, {})[exercise_id] = mark
80 del self.marks[user_id][exercise_id]
82 def get_exercise_marks_by_examiner(self, exercise_id):
84 for examiner_id, examiner_marks in self.marks.items():
85 mark = examiner_marks.get(exercise_id, None)
87 marks[examiner_id] = mark
90 def get_final_exercise_mark(self, exercise_id):
91 # exercise = exercises[int(exercise_id)-1]
92 exercise = [e for e in exercises if str(e['id']) == str(exercise_id)][0]
93 if exercise_checked_manually(exercise):
94 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
95 if len(marks_by_examiner):
96 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
102 answer = json.loads(self.answers)[exercise_id]['closed_part']
104 if t == 'edumed_uporzadkuj':
105 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
106 if t == 'edumed_przyporzadkuj':
108 for bucket_id, items in answer.items():
109 for item_id in items:
111 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
112 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
114 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
116 toret += exercise['points_per_hit']
118 if t == 'edumed_wybor':
119 if len(exercise['answer']) == 1:
120 if len(answer) and int(answer[0]) == exercise['answer'][0]:
121 return exercise['points']
126 if exercise.get('answer_mode', None) == 'all_or_nothing':
127 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
129 for answer_id in map(int, answer):
130 if answer_id in exercise['answer']:
131 toret += exercise['points_per_hit']
133 if t == 'edumed_prawdafalsz':
135 for idx, statement in enumerate(exercise['statements']):
136 if statement[1] == 'ignore':
138 if answer[idx] == 'true':
140 elif answer[idx] == 'false':
144 if given == statement[1]:
145 toret += exercise['points_per_hit']
147 raise NotImplementedError
150 def final_result(self):
152 # for exercise_id in map(str,range(1, len(exercises) + 1)):
153 for exercise_id in [str(x['id']) for x in exercises]:
154 mark = self.get_final_exercise_mark(exercise_id)
160 def final_result_as_string(self):
161 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
164 class Attachment(models.Model):
165 submission = models.ForeignKey(Submission)
166 exercise_id = models.IntegerField()
167 tag = models.CharField(max_length=128, null=True, blank=True)
168 file = models.FileField(upload_to='wtem/attachment')
171 class Assignment(models.Model):
172 user = models.ForeignKey(User, unique=True)
173 exercises = JSONField()
176 if not isinstance(self.exercises, list):
177 raise ValidationError(_('Assigned exercises must be declared in a list format'))
178 # for exercise in self.exercises:
179 # if not isinstance(exercise, int) or exercise < 1:
180 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
182 def __unicode__(self):
183 return self.user.username + ': ' + ','.join(map(str, self.exercises))
186 class Confirmation(models.Model):
187 first_name = models.CharField(max_length=100)
188 last_name = models.CharField(max_length=100)
189 email = models.EmailField(max_length=100, unique=True)
190 contact = models.ForeignKey(Contact, null=True)
191 key = models.CharField(max_length=30)
192 confirmed = models.BooleanField(default=False)
195 def create(cls, first_name, last_name, email, contact=None, key=None):
198 key=key if key else make_key(30),
199 first_name=first_name,
207 def absolute_url(self):
208 return reverse('student_confirmation', args=(self.id, self.key))
211 def exercise_checked_manually(exercise):
212 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise