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