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 assert type(posted_answers) == dict, 'answers not dict'
53 assert len(posted_answers) == 1, 'answers not single'
54 exercise_id = posted_answers.keys()[0]
55 i, exercise = submission.current_exercise()
56 assert exercise_id == str(exercise['id']), 'wrong exercise id'
57 for answer in posted_answers.values():
58 answers[exercise_id] = answer
59 submission.answers = json.dumps(answers)
61 for name, attachment_file in self.files.items():
62 m = re.match(r'attachment(?:__(.*))?', name)
63 tag = m.group(1) or None
64 attachment, created = Attachment.objects.get_or_create(
65 submission=submission, exercise_id=exercise_id, tag=tag)
66 attachment.file = attachment_file