prettify abbreviated filename
[edumed.git] / stage2 / forms.py
index f7d248e..92af3a0 100644 (file)
@@ -1,7 +1,6 @@
 # -*- coding: utf-8 -*-
 from django import forms
 from django.conf import settings
-from django.core.exceptions import ValidationError
 from django.template.defaultfilters import filesizeformat
 
 from stage2.models import Attachment, Mark
@@ -12,10 +11,13 @@ class AttachmentForm(forms.ModelForm):
         model = Attachment
         fields = ['file']
 
-    def __init__(self, assignment, file_no, label, *args, **kwargs):
+    def __init__(self, assignment, file_no, label, extensions=None, *args, **kwargs):
         prefix = 'att%s-%s' % (assignment.id, file_no)
         super(AttachmentForm, self).__init__(*args, prefix=prefix, **kwargs)
         self.fields['file'].label = label
+        if extensions:
+            self.fields['file'].widget.attrs = {'data-ext': '|'.join(extensions)}
+        self.extensions = extensions
 
     def clean_file(self):
         file = self.cleaned_data['file']
@@ -23,6 +25,8 @@ class AttachmentForm(forms.ModelForm):
             raise forms.ValidationError(
                 'Please keep filesize under %s. Current filesize: %s' % (
                     filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(file.size)))
+        if self.extensions and ('.' not in file.name or file.name.rsplit('.', 1)[1].lower() not in self.extensions):
+            raise forms.ValidationError('Incorrect extension, should be one of: %s' % ', '.join(self.extensions))
         return file
 
 
@@ -42,7 +46,7 @@ class MarkForm(forms.ModelForm):
     def clean_points(self):
         points = self.cleaned_data['points']
         if points > self.answer.assignment.max_points:
-            raise ValidationError('Too many points for this assignment')
+            raise forms.ValidationError('Too many points for this assignment')
         if points < 0:
-            raise ValidationError('Points cannot be negative')
+            raise forms.ValidationError('Points cannot be negative')
         return points