Code

Ticket #5175: formsets-required_forms-5897.diff

File formsets-required_forms-5897.diff, 2.5 KB (added by Simon Litchfield <simon@…>, 7 years ago)

Adds formset.formset_errors ErrorList if number of required_forms is not met

Line 
1Index: django/newforms/formsets.py
2===================================================================
3--- django/newforms/formsets.py (revision 5897)
4+++ django/newforms/formsets.py (working copy)
5@@ -21,7 +21,7 @@
6     """A collection of instances of the same Form class."""
7 
8     def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None):
9-        self.is_bound = data is not None and files is not None
10+        self.is_bound = data is not None or files is not None
11         self.prefix = prefix or 'form'
12         self.auto_id = auto_id
13         self.data = data
14@@ -61,6 +61,11 @@
15                     kwargs['files'] = self.files
16                 add_form = FormClass(**kwargs)
17                 self.add_fields(add_form, i)
18+                # HACK: Form is empty, lets re-create without data so it doesn't trip validation
19+                if self.data and add_form.is_empty():
20+                    del(kwargs['data'])
21+                    add_form = FormClass(**kwargs)
22+                    self.add_fields(add_form, i)
23                 add_forms.append(add_form)
24             self._add_forms = add_forms
25         return self._add_forms
26@@ -69,7 +74,7 @@
27     def _get_change_forms(self):
28         """Return a list of all the change forms in this ``FormSet``."""
29         FormClass = self.form_class
30-        if not hasattr(self, '_add_forms'):
31+        if not hasattr(self, '_change_forms'):
32             change_forms = []
33             for i in range(0, self.change_form_count):
34                 kwargs = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
35@@ -93,7 +98,7 @@
36     def full_clean(self):
37         """Cleans all of self.data and populates self.__errors and self.cleaned_data."""
38         is_valid = True
39-        errors = []
40+        errors = ErrorList()
41         if not self.is_bound: # Stop further processing.
42             self.__errors = errors
43             return
44@@ -134,6 +139,10 @@
45         if self.orderable:
46             cleaned_data.sort(lambda x,y: x[ORDERING_FIELD_NAME] - y[ORDERING_FIELD_NAME])
47 
48+        if is_valid and self.required_forms > len(cleaned_data):
49+            errors.insert(0, 'asdf')
50+            is_valid = False
51+           
52         if is_valid:
53             self.cleaned_data = cleaned_data
54             self.deleted_data = deleted_data
55@@ -151,6 +160,8 @@
56         return '%s-%s' % (self.prefix, index)
57 
58     def is_valid(self):
59+        if not self.is_bound:
60+            return False
61         self.full_clean()
62         return self._is_valid
63