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'
27 def get_exercise_by_id(exercise_id):
28 return [e for e in exercises if str(e['id']) == str(exercise_id)][0]
33 random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)
34 for i in range(length))
37 class CompetitionState(models.Model):
43 (BEFORE, u'przed rozpoczęciem'),
44 (DURING, u'w trakcie'),
45 (AFTER, u'po zakończeniu'),
47 state = models.CharField(choices=STATE_CHOICES, max_length=16)
51 return cls.objects.get().state
54 class Submission(models.Model):
55 contact = models.ForeignKey(Contact, null=True)
56 key = models.CharField(max_length=30, unique=True)
57 first_name = models.CharField(max_length=100)
58 last_name = models.CharField(max_length=100)
59 email = models.EmailField(max_length=100, unique=True)
60 answers = models.CharField(max_length=65536, null=True, blank=True)
61 key_sent = models.BooleanField(default=False)
62 marks = JSONField(default={})
63 examiners = models.ManyToManyField(User, null=True, blank=True)
64 end_time = models.CharField(max_length=5, null=True, blank=True)
65 random_seed = models.IntegerField()
67 def __unicode__(self):
68 return ', '.join((self.last_name, self.first_name, self.email))
71 def generate_key(cls):
73 while not key or key in [record['key'] for record in cls.objects.values('key')]:
78 def create(cls, first_name, last_name, email, key=None, contact=None):
81 key=key if key else Submission.generate_key(),
82 first_name=first_name,
85 random_seed=random.randint(-2147483648, 2147483647)
91 def competition_link(self):
92 return reverse('form_single', kwargs={'submission_id': self.id, 'key': self.key})
94 def get_answers(self):
95 return json.loads(self.answers) if self.answers else {}
97 def shuffled_exercise_ids(self):
98 exercise_ids = [e['id'] for e in exercises]
99 seeded_random = random.Random(self.random_seed)
100 seeded_random.shuffle(exercise_ids)
103 def current_exercise(self):
104 answers = self.get_answers()
105 for i, id in enumerate(self.shuffled_exercise_ids(), 1):
106 if str(id) not in answers:
107 return i, get_exercise_by_id(id)
110 def get_mark(self, user_id, exercise_id):
112 user_id = str(user_id)
113 exercise_id = str(exercise_id)
114 if self.marks and user_id in self.marks:
115 mark = self.marks[user_id].get(exercise_id, None)
118 def set_mark(self, user_id, exercise_id, mark):
119 user_id = str(user_id)
120 exercise_id = str(exercise_id)
124 self.marks.setdefault(user_id, {})[exercise_id] = mark
126 del self.marks[user_id][exercise_id]
128 def get_exercise_marks_by_examiner(self, exercise_id):
130 for examiner_id, examiner_marks in self.marks.items():
131 mark = examiner_marks.get(exercise_id, None)
133 marks[examiner_id] = mark
136 def get_final_exercise_mark(self, exercise_id):
137 exercise = get_exercise_by_id(exercise_id)
138 if exercise_checked_manually(exercise):
139 marks_by_examiner = self.get_exercise_marks_by_examiner(exercise_id)
140 if len(marks_by_examiner):
141 return sum(map(float, marks_by_examiner.values())) / float(len(marks_by_examiner))
147 answer = json.loads(self.answers)[exercise_id]['closed_part']
149 if t == 'edumed_uporzadkuj':
150 return exercise['points'] if map(int, answer) == exercise['answer'] else 0
151 if t == 'edumed_przyporzadkuj':
153 for bucket_id, items in answer.items():
154 for item_id in items:
156 if exercise.get('answer_mode', None) == 'possible_buckets_for_item':
157 is_correct = int(bucket_id) in exercise['answer'].get(item_id)
159 is_correct = int(item_id) in exercise['answer'].get(bucket_id, [])
161 toret += exercise['points_per_hit']
163 if t == 'edumed_wybor':
164 if len(exercise['answer']) == 1:
165 if len(answer) and int(answer[0]) == exercise['answer'][0]:
166 return exercise['points']
171 if exercise.get('answer_mode', None) == 'all_or_nothing':
172 toret = exercise['points'] if map(int, answer) == exercise['answer'] else 0
174 for answer_id in map(int, answer):
175 if answer_id in exercise['answer']:
176 toret += exercise['points_per_hit']
178 if t == 'edumed_prawdafalsz':
180 for idx, statement in enumerate(exercise['statements']):
181 if statement[1] == 'ignore':
183 if answer[idx] == 'true':
185 elif answer[idx] == 'false':
189 if given == statement[1]:
190 toret += exercise['points_per_hit']
192 raise NotImplementedError
195 def final_result(self):
197 # for exercise_id in map(str,range(1, len(exercises) + 1)):
198 for exercise_id in [str(x['id']) for x in exercises]:
199 mark = self.get_final_exercise_mark(exercise_id)
205 def final_result_as_string(self):
206 return ('%.2f' % self.final_result).rstrip('0').rstrip('.')
209 class Attachment(models.Model):
210 submission = models.ForeignKey(Submission)
211 exercise_id = models.IntegerField()
212 tag = models.CharField(max_length=128, null=True, blank=True)
213 file = models.FileField(upload_to='wtem/attachment')
216 class Assignment(models.Model):
217 user = models.ForeignKey(User, unique=True)
218 exercises = JSONField()
221 if not isinstance(self.exercises, list):
222 raise ValidationError(_('Assigned exercises must be declared in a list format'))
223 # for exercise in self.exercises:
224 # if not isinstance(exercise, int) or exercise < 1:
225 # raise ValidationError(_('Invalid exercise id: %s' % exercise))
227 def __unicode__(self):
228 return self.user.username + ': ' + ','.join(map(str, self.exercises))
231 class Confirmation(models.Model):
232 first_name = models.CharField(max_length=100)
233 last_name = models.CharField(max_length=100)
234 email = models.EmailField(max_length=100, unique=True)
235 contact = models.ForeignKey(Contact, null=True)
236 key = models.CharField(max_length=30)
237 confirmed = models.BooleanField(default=False)
240 ordering = ['contact__contact']
243 def create(cls, first_name, last_name, email, contact=None, key=None):
246 key=key if key else make_key(30),
247 first_name=first_name,
255 def absolute_url(self):
256 return reverse('student_confirmation', args=(self.id, self.key))
258 def readable_contact(self):
259 return '%s <%s>' % (self.contact.body.get('przewodniczacy'), self.contact.contact)
262 return timezone.now() - self.contact.created_at
264 def readable_age(self):
266 return '%s dni, %s godzin' % (td.days, td.seconds/3600)
269 mail_subject = render_to_string('contact/olimpiada/student_mail_subject.html').strip()
270 mail_body = render_to_string(
271 'contact/olimpiada/student_mail_body.html', {'confirmation': self})
273 validate_email(self.email)
274 except ValidationError:
277 send_mail(mail_subject, mail_body, 'olimpiada@nowoczesnapolska.org.pl', [self.email],
281 def exercise_checked_manually(exercise):
282 return (exercise['type'] in ('open', 'file_upload')) or 'open_part' in exercise