- commit
- 3311ec2e3d6b57d813e43cba0520b6fc3e7bc99c
- parent
- cf0d359191bc32a586cbe32a0cf79e30567f9d97
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2019-09-15 09:07
add RestrictedFileField
Diffstat
| A | utils/file_field.py | 33 | +++++++++++++++++++++++++++++++++ |
1 files changed, 33 insertions, 0 deletions
diff --git a/utils/file_field.py b/utils/file_field.py
@@ -0,0 +1,33 @@
-1 1 from django import forms
-1 2 from django.utils.translation import gettext_lazy as _
-1 3
-1 4 import magic
-1 5
-1 6
-1 7 class RestrictedFileField(forms.FileField):
-1 8 def __init__(self, *args, **kwargs):
-1 9 self.content_types = kwargs.pop('content_types', [])
-1 10 self.max_upload_size = kwargs.pop('max_upload_size', 0)
-1 11 super().__init__(*args, **kwargs)
-1 12
-1 13 def to_python(self, data):
-1 14 f = super().to_python(data)
-1 15 if f is None:
-1 16 return None
-1 17
-1 18 if f.size > self.max_upload_size:
-1 19 raise forms.ValidationError(_('File is too big.'), code='size')
-1 20
-1 21 content_type = magic.detect_from_content(f.read(1024)).mime_type
-1 22 if content_type not in self.content_types:
-1 23 raise forms.ValidationError(
-1 24 _('Filetype not supported.'), code='content_type'
-1 25 )
-1 26
-1 27 return f
-1 28
-1 29 def widget_attrs(self, widget):
-1 30 attrs = super().widget_attrs(widget)
-1 31 if self.content_types:
-1 32 attrs.setdefault('accept', ','.join(self.content_types))
-1 33 return attrs