504fd26df1209b1faded7076f0c6ebefec62a9f2
[edumed.git] / wtem / forms.py
1 import os
2 import re
3
4 from django import forms
5 from django.utils import simplejson
6
7 from .models import Submission, Attachment, exercises
8
9
10 class WTEMForm(forms.ModelForm):
11     class Meta:
12         model = Submission
13         fields = ('answers',)
14
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                 continue
20             self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required = False)
21
22     def save(self, commit=True):
23         submission = super(WTEMForm, self).save(commit=commit)
24         for name, file in self.files.items():
25             m = re.match(r'attachment_for_(\d+)(?:__(.*))?', name)
26             exercise_id = int(m.group(1))
27             tag = m.group(2) or None
28             try:
29                 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise_id, tag=tag)
30             except Attachment.DoesNotExist:
31                 attachment = Attachment(submission = submission, exercise_id = exercise_id, tag=tag)
32             attachment.file = file
33             attachment.save()
34