Skip to content

Instantly share code, notes, and snippets.

@devwaseem
Created November 9, 2022 11:38
Show Gist options
  • Save devwaseem/50576ef2345ee45770657d6f3fa78af0 to your computer and use it in GitHub Desktop.
Save devwaseem/50576ef2345ee45770657d6f3fa78af0 to your computer and use it in GitHub Desktop.
Max File size validator for Django
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
@deconstructible
class MaxFileSizeValidatorInMb:
message = _("The file size is %(current_file_size)s MB, exceeding the maximum file size of %(max_file_size)s MB ")
code = "file_size_exceeded"
def __init__(self, max_size_in_mb=None, message=None, code=None):
self.max_size_in_mb = max_size_in_mb
if message is not None:
self.message = message
if code is not None:
self.code = code
def __call__(self, value):
current_file_size = (value.size / 1024) / 1024
max_file_size = self.max_size_in_mb * 1024 * 1024
if value.size > max_file_size:
raise ValidationError(
self.message,
code=self.code,
params={
"current_file_size": str(round(current_file_size, 2)),
"max_file_size": str(self.max_size_in_mb),
},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.max_size_in_mb == other.max_size_in_mb
and self.message == other.message
and self.code == other.code
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment