Code

Ticket #13584: allow_empty_file_formfield_sloppy_test.diff

File allow_empty_file_formfield_sloppy_test.diff, 2.4 KB (added by erikr, 4 years ago)
Line 
1Index: django/forms/fields.py
2===================================================================
3--- django/forms/fields.py      (revision 13301)
4+++ django/forms/fields.py      (working copy)
5@@ -439,6 +439,7 @@
6 
7     def __init__(self, *args, **kwargs):
8         self.max_length = kwargs.pop('max_length', None)
9+        self.allow_empty_file = kwargs.pop('allow_empty_file', False)
10         super(FileField, self).__init__(*args, **kwargs)
11 
12     def to_python(self, data):
13@@ -457,7 +458,7 @@
14             raise ValidationError(self.error_messages['max_length'] % error_values)
15         if not file_name:
16             raise ValidationError(self.error_messages['invalid'])
17-        if not file_size:
18+        if not self.allow_empty_file and not file_size:
19             raise ValidationError(self.error_messages['empty'])
20 
21         return data
22Index: tests/regressiontests/forms/fields.py
23===================================================================
24--- tests/regressiontests/forms/fields.py       (revision 13303)
25+++ tests/regressiontests/forms/fields.py       (working copy)
26@@ -463,6 +463,10 @@
27         self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
28         self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'))))
29 
30+    def test_filefield_37(self):
31+        f = FileField(allow_empty_file = True)
32+        self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', ''))))
33+
34     # URLField ##################################################################
35 
36     def test_urlfield_37(self):
37Index: docs/ref/forms/fields.txt
38===================================================================
39--- docs/ref/forms/fields.txt   (revision 13301)
40+++ docs/ref/forms/fields.txt   (working copy)
41@@ -513,9 +513,12 @@
42     * Empty value: ``None``
43     * Normalizes to: An ``UploadedFile`` object that wraps the file content
44       and file name into a single object.
45-    * Validates that non-empty file data has been bound to the form.
46+    * Can validate that non-empty file data has been bound to the form.
47     * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``
48 
49+Has one optional argument for validation, ``allow_empty_file``. If provided,
50+validation will succeed even if the file content is empty.
51+
52 To learn more about the ``UploadedFile`` object, see the :ref:`file uploads
53 documentation <topics-http-file-uploads>`.
54