Fixes #3314, #3331: Various minor fixes.
[edumed.git] / wtem / forms.py
1 import os
2
3 from django import forms
4 from django.utils import simplejson
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):
22         submission = super(WTEMForm, self).save()
23         for name, file in self.files.items():
24             exercise_id = int(name.split('_')[-1])
25             try:
26                 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise_id)
27             except Attachment.DoesNotExist:
28                 attachment = Attachment(submission = submission, exercise_id = exercise_id)
29             attachment.file = file
30             attachment.save()
31