f7d248e41b4721a1a0003fe7f7a6e63f4979ca58
[edumed.git] / stage2 / forms.py
1 # -*- coding: utf-8 -*-
2 from django import forms
3 from django.conf import settings
4 from django.core.exceptions import ValidationError
5 from django.template.defaultfilters import filesizeformat
6
7 from stage2.models import Attachment, Mark
8
9
10 class AttachmentForm(forms.ModelForm):
11     class Meta:
12         model = Attachment
13         fields = ['file']
14
15     def __init__(self, assignment, file_no, label, *args, **kwargs):
16         prefix = 'att%s-%s' % (assignment.id, file_no)
17         super(AttachmentForm, self).__init__(*args, prefix=prefix, **kwargs)
18         self.fields['file'].label = label
19
20     def clean_file(self):
21         file = self.cleaned_data['file']
22         if file.size > settings.MAX_UPLOAD_SIZE:
23             raise forms.ValidationError(
24                 'Please keep filesize under %s. Current filesize: %s' % (
25                     filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(file.size)))
26         return file
27
28
29 class MarkForm(forms.ModelForm):
30     class Meta:
31         model = Mark
32         fields = ['points']
33         widgets = {
34             'points': forms.TextInput(attrs={'type': 'number', 'min': 0, 'step': '0.5'})
35         }
36
37     def __init__(self, answer, *args, **kwargs):
38         super(MarkForm, self).__init__(*args, **kwargs)
39         self.answer = answer
40         self.fields['points'].widget.attrs['max'] = answer.assignment.max_points
41
42     def clean_points(self):
43         points = self.cleaned_data['points']
44         if points > self.answer.assignment.max_points:
45             raise ValidationError('Too many points for this assignment')
46         if points < 0:
47             raise ValidationError('Points cannot be negative')
48         return points