1 # -*- coding: utf-8 -*-
7 from django.core.validators import validate_email
8 from django.db import models
9 from django.contrib.auth.models import User
10 from django.core.exceptions import ValidationError
11 from django.core.mail import send_mail
12 from django.core.urlresolvers import reverse
13 from django.template.loader import render_to_string
14 from django.utils import timezone
15 from django.utils.translation import ugettext as _
16 from jsonfield import JSONField
18 from contact.models import Contact
20 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
21 exercises = json.loads(f.read())
24 DEBUG_KEY = 'smerfetka159'
29 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
30 for i in range(length))
33 class Submission(models.Model):
34 contact = models.ForeignKey(Contact, null=True)
35 key = models.CharField(max_length=30, unique=True)
36 first_name = models.CharField(max_length=100)
37 last_name = models.CharField(max_length=100)
38 email = models.EmailField(max_length=100, unique=True)
39 answers = models.CharField(max_length=65536, null=True, blank=True)
40 key_sent = models.BooleanField(default=False)
41 marks = JSONField(default={})
42 examiners = models.ManyToManyField(User, null=True, blank=True)
43 end_time = models.CharField(max_length=5, null=True, blank=True)
45 def __unicode__(self):
46 return ', '.join((self.last_name, self.first_name, self.email))
49 def generate_key(cls):
51 while not key or key in [record['key'] for record in cls.objects.values('key')]:
56 def create(cls, first_name, last_name, email, key=None, contact=None):
59 key=key if key else Submission.generate_key(),
60 first_name=first_name,
68 def get_mark(self, user_id, exercise_id):
70 user_id = str(user_id)
71 exercise_id = str(exercise_id)
72 if self.marks and user_id in self.marks:
73 mark = self.marks[user_id].get(exercise_id, None)
76 def set_mark(self, user_id, exercise_id, mark):
77 user_id = str(user_id)
78 exercise_id = str(exercise_id)
82 self.marks.setdefault(user_id, {})[exercise_id] = mark
84 del self.marks[user_id][exercise_id]
86 def get_exercise_marks_by_examiner(self, exercise_id):
88 for examiner_id, examiner_marks in self.marks.items():
89 mark = examiner_marks.get(exercise_id, None)
91 marks[examiner_id] = mark
94 def get_final_exercise_mark(self, exercise_id):
95 # exercise = exercises[int(exercise_id)-1]
96 exercise = [e for e in exercises if str(e['id']) == str(exercise_id)][0]
97 if exercise_checked_manually(exercise):
98 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
99 if len(marks_by_examiner):
100 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
106 answer = json.loads(self.answers)[exercise_id]['closed_part']
108 if t == 'edumed_uporzadkuj':
109 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
110 if t == 'edumed_przyporzadkuj':
112 for bucket_id, items in answer.items():
113 for item_id in items:
115 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
116 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
118 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
120 toret += exercise['points_per_hit']
122 if t == 'edumed_wybor':
123 if len(exercise['answer']) == 1:
124 if len(answer) and int(answer[0]) == exercise['answer'][0]:
125 return exercise['points']
130 if exercise.get('answer_mode', None) == 'all_or_nothing':
131 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
133 for answer_id in map(int, answer):
134 if answer_id in exercise['answer']:
135 toret += exercise['points_per_hit']
137 if t == 'edumed_prawdafalsz':
139 for idx, statement in enumerate(exercise['statements']):
140 if statement[1] == 'ignore':
142 if answer[idx] == 'true':
144 elif answer[idx] == 'false':
148 if given == statement[1]:
149 toret += exercise['points_per_hit']
151 raise NotImplementedError
154 def final_result(self):
156 # for exercise_id in map(str,range(1, len(exercises) + 1)):
157 for exercise_id in [str(x['id']) for x in exercises]:
158 mark = self.get_final_exercise_mark(exercise_id)
164 def final_result_as_string(self):
165 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
168 class Attachment(models.Model):
169 submission = models.ForeignKey(Submission)
170 exercise_id = models.IntegerField()
171 tag = models.CharField(max_length=128, null=True, blank=True)
172 file = models.FileField(upload_to='wtem/attachment')
175 class Assignment(models.Model):
176 user = models.ForeignKey(User, unique=True)
177 exercises = JSONField()
180 if not isinstance(self.exercises, list):
181 raise ValidationError(_('Assigned exercises must be declared in a list format'))
182 # for exercise in self.exercises:
183 # if not isinstance(exercise, int) or exercise < 1:
184 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
186 def __unicode__(self):
187 return self.user.username + ': ' + ','.join(map(str, self.exercises))
190 class Confirmation(models.Model):
191 first_name = models.CharField(max_length=100)
192 last_name = models.CharField(max_length=100)
193 email = models.EmailField(max_length=100, unique=True)
194 contact = models.ForeignKey(Contact, null=True)
195 key = models.CharField(max_length=30)
196 confirmed = models.BooleanField(default=False)
202 def create(cls, first_name, last_name, email, contact=None, key=None):
205 key=key if key else make_key(30),
206 first_name=first_name,
214 def absolute_url(self):
215 return reverse('student_confirmation', args=(self.id, self.key))
217 def readable_contact(self):
218 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
221 return timezone.now() - self.contact.created_at
223 def readable_age(self):
225 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
228 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
229 mail_body = render_to_string(
230 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
232 validate_email(self.email)
233 except ValidationError:
236 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
240 def exercise_checked_manually(exercise):
241 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise