Some archeology.
[edumed.git] / wtem / forms.py
1 # -*- coding: utf-8 -*-
2 import re
3
4 from django import forms
5
6 from .models import Submission, Attachment, exercises
7
8
9 class WTEMForm(forms.ModelForm):
10     class Meta:
11         model = Submission
12         fields = ('answers',)
13
14     def __init__(self, *args, **kwargs):
15         super(WTEMForm, self).__init__(*args, **kwargs)
16         for exercise in exercises:
17             if exercise['type'] != 'file_upload':
18                 continue
19             self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required=False)
20
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
27             try:
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
32             attachment.save()