question update
[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
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
17         ## @@ move this one level up
18         f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
19         exercises = simplejson.loads(f.read())
20         f.close()
21
22         for exercise in exercises:
23             if exercise['type'] != 'file_upload':
24                 continue
25             self.fields['attachment_for_' + str(exercise['id'])] = forms.FileField(required = False)
26
27     def save(self):
28         submission = super(WTEMForm, self).save()
29         for name, file in self.files.items():
30             exercise_id = int(name.split('_')[-1])
31             try:
32                 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise_id)
33             except Attachment.DoesNotExist:
34                 attachment = Attachment(fsubmission = submission, exercise_id = exercise_id)
35             attachment.file = file
36             attachment.save()
37