+class AssignmentFieldForm(forms.Form):
+ value = forms.CharField(required=False)
+ assignment_id = forms.CharField(widget=forms.HiddenInput)
+
+ def __init__(self, label, field_no, options, answer, *args, **kwargs):
+ prefix = 'field%s-%s' % (answer.id, field_no)
+ super(AssignmentFieldForm, self).__init__(prefix=prefix, *args, **kwargs)
+ self.answer = answer
+ self.label = label
+ self.fields['value'].label = label
+ self.type = options['type']
+ self.fields['assignment_id'].initial = answer.assignment.id
+ if self.type == 'options':
+ option_set = FieldOptionSet.objects.get(name=options['option_set'])
+ self.fields['value'].widget = forms.Select(choices=option_set.choices(answer))
+ options = answer.fieldoption_set.all()
+ if options:
+ self.fields['value'].initial = options.get().id
+ else:
+ value = answer.field_values.get(label)
+ self.fields['value'].initial = value or ''
+
+ def clean_value(self):
+ if self.type == 'options':
+ value = self.cleaned_data['value']
+ if value:
+ option = FieldOption.objects.get(id=int(value))
+ if option.answer != self.answer and option.answer is not None:
+ raise forms.ValidationError(u'Ta opcja została już wybrana przez kogoś innego.')
+ return option
+ return self.cleaned_data['value']
+
+ def save(self):
+ value = self.cleaned_data['value']
+ if self.type == 'options':
+ option = value
+ if option:
+ if option.answer != self.answer:
+ # not thread-safe :/
+ assert not option.answer
+ for opt in self.answer.fieldoption_set.all():
+ opt.answer = None
+ opt.save()
+ option.answer = self.answer
+ option.save()
+ else:
+ for opt in self.answer.fieldoption_set.all():
+ opt.answer = None
+ opt.save()
+ else:
+ self.answer.field_values[self.label] = value
+ self.answer.save()
+
+