#46 MIME Type check
* adds file mime type check on NewDocumentForm * adds file size check on NewDocumentForm * adds is_xy_valid methods as classmethods on AbstractDocument * adds translations for error messages * updates help text on NewDocumentForm file field
This commit is contained in:
@@ -354,7 +354,7 @@ class NewDocumentForm(BaseModalForm):
|
||||
file = forms.FileField(
|
||||
label=_("File"),
|
||||
label_suffix=_(""),
|
||||
help_text=_("Must be smaller than 15 Mb"),
|
||||
help_text=_("Allowed formats: pdf, jpg, png. Max size 15 MB."),
|
||||
widget=forms.FileInput(
|
||||
attrs={
|
||||
"class": "form-control-file",
|
||||
@@ -391,6 +391,28 @@ class NewDocumentForm(BaseModalForm):
|
||||
if not self.document_model:
|
||||
raise NotImplementedError("Unsupported document type for {}".format(self.instance.__class__))
|
||||
|
||||
def is_valid(self):
|
||||
super_valid = super().is_valid()
|
||||
|
||||
_file = self.cleaned_data.get("file", None)
|
||||
|
||||
mime_type_valid = self.document_model.is_mime_type_valid(_file)
|
||||
if not mime_type_valid:
|
||||
self.add_error(
|
||||
"file",
|
||||
_("Unsupported file type")
|
||||
)
|
||||
|
||||
file_size_valid = self.document_model.is_file_size_valid(_file)
|
||||
if not file_size_valid:
|
||||
self.add_error(
|
||||
"file",
|
||||
_("File too large")
|
||||
)
|
||||
|
||||
file_valid = mime_type_valid and file_size_valid
|
||||
return super_valid and file_valid
|
||||
|
||||
def save(self):
|
||||
with transaction.atomic():
|
||||
action = UserActionLogEntry.get_created_action(self.user)
|
||||
|
||||
@@ -5,6 +5,7 @@ Contact: michel.peltriaux@sgdnord.rlp.de
|
||||
Created on: 15.11.21
|
||||
|
||||
"""
|
||||
import mimetypes
|
||||
import os
|
||||
|
||||
from django.db import models
|
||||
@@ -62,6 +63,15 @@ class AbstractDocument(BaseResource):
|
||||
file = models.FileField()
|
||||
comment = models.TextField()
|
||||
|
||||
_accepted_mime_types = {
|
||||
mimetypes.types_map[".pdf"],
|
||||
mimetypes.types_map[".jpg"],
|
||||
mimetypes.types_map[".jpeg"],
|
||||
mimetypes.types_map[".png"],
|
||||
}
|
||||
# _maximum_file_size in MB
|
||||
_maximum_file_size = 15
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
@@ -82,3 +92,12 @@ class AbstractDocument(BaseResource):
|
||||
pass
|
||||
super().delete(using=using, keep_parents=keep_parents)
|
||||
|
||||
@classmethod
|
||||
def is_mime_type_valid(cls, _file: str):
|
||||
mime_type = _file.content_type
|
||||
return mime_type in cls._accepted_mime_types
|
||||
|
||||
@classmethod
|
||||
def is_file_size_valid(cls, _file):
|
||||
max_size = cls._maximum_file_size * pow(1000, 2)
|
||||
return _file.size <= max_size
|
||||
|
||||
Reference in New Issue
Block a user