Ticket #14787: 14787.diff

File 14787.diff, 2.3 KB (added by ANUBHAV JOSHI, 10 years ago)

max_size for FileField

  • django/forms/fields.py

    diff --git a/django/forms/fields.py b/django/forms/fields.py
    index ab746e4..48dde6a 100644
    a b class FileField(Field):  
    571571            'Ensure this filename has at most %(max)d character (it has %(length)d).',
    572572            'Ensure this filename has at most %(max)d characters (it has %(length)d).',
    573573            'max'),
     574        'max_size': _("The submitted file exceeds the maximum size specified."),
    574575        'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
    575576    }
    576577
    577578    def __init__(self, *args, **kwargs):
    578579        self.max_length = kwargs.pop('max_length', None)
    579580        self.allow_empty_file = kwargs.pop('allow_empty_file', False)
     581        self.max_size = kwargs.pop('max_size', None)  # size in mb
    580582        super(FileField, self).__init__(*args, **kwargs)
    581583
    582584    def to_python(self, data):
    class FileField(Field):  
    597599            raise ValidationError(self.error_messages['invalid'], code='invalid')
    598600        if not self.allow_empty_file and not file_size:
    599601            raise ValidationError(self.error_messages['empty'], code='empty')
     602        if self.max_size is not None and file_size > (self.max_size * 2 ** 20):
     603            raise ValidationError(self.error_messages['max_size'], code='max_size')
    600604
    601605        return data
    602606
  • tests/forms_tests/tests/test_error_messages.py

    diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
    index 94f5424..fac7205 100644
    a b class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):  
    143143            'invalid': 'INVALID',
    144144            'missing': 'MISSING',
    145145            'empty': 'EMPTY FILE',
     146            'max_size': 'EXCEEDS SIZE'
    146147        }
    147         f = FileField(error_messages=e)
     148        f = FileField(error_messages=e, max_size=2 ** (-20))
    148149        self.assertFormErrors(['REQUIRED'], f.clean, '')
    149150        self.assertFormErrors(['INVALID'], f.clean, 'abc')
    150151        self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
    151152        self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))
     153        self.assertFormErrors(['EXCEEDS SIZE'], f.clean, SimpleUploadedFile('name', b'test file'))
    152154
    153155    def test_urlfield(self):
    154156        e = {
Back to Top