1 # -*- coding: utf-8 -*-
5 from django import forms
7 from .models import Submission, Attachment, exercises
10 class WTEMForm(forms.ModelForm):
15 def __init__(self, *args, **kwargs):
16 super(WTEMForm, self).__init__(*args, **kwargs)
17 for exercise in exercises:
18 if exercise['type'] == 'file_upload':
19 self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required=False)
21 def save(self, commit=True):
22 submission = super(WTEMForm, self).save(commit=commit)
23 for name, attachment_file in self.files.items():
24 m = re.match(r'attachment_for_(\d+)(?:__(.*))?', name)
25 exercise_id = int(m.group(1))
26 tag = m.group(2) or None
28 attachment = Attachment.objects.get(submission=submission, exercise_id=exercise_id, tag=tag)
29 except Attachment.DoesNotExist:
30 attachment = Attachment(submission=submission, exercise_id=exercise_id, tag=tag)
31 attachment.file = attachment_file
35 class WTEMSingleForm(forms.ModelForm):
36 answers = forms.CharField()
42 def __init__(self, *args, **kwargs):
43 super(WTEMSingleForm, self).__init__(*args, **kwargs)
44 i, exercise = self.instance.current_exercise()
45 if exercise and exercise['type'] == 'file_upload':
46 self.fields['attachment'] = forms.FileField(required=False)
48 def save(self, commit=True):
49 submission = self.instance
50 answers = submission.get_answers()
51 posted_answers = json.loads(self.cleaned_data['answers'])
52 if type(posted_answers) != dict:
53 raise ValueError('answers not dict')
54 if len(posted_answers) != 1:
55 raise ValueError('answers not single')
56 exercise_id, answer = posted_answers.items()[0]
58 if answers.get(exercise_id) == answer:
60 i, exercise = submission.current_exercise()
61 if exercise_id != str(exercise['id']):
62 raise ValueError('wrong exercise id')
63 for answer in posted_answers.values():
64 answers[exercise_id] = answer
65 submission.answers = json.dumps(answers)
67 for name, attachment_file in self.files.items():
68 m = re.match(r'attachment(?:__(.*))?', name)
69 tag = m.group(1) or None
70 attachment, created = Attachment.objects.get_or_create(
71 submission=submission, exercise_id=exercise_id, tag=tag)
72 attachment.file = attachment_file