Code

Ticket #14655: formset-iterable-2.diff

File formset-iterable-2.diff, 1.7 KB (added by kenth, 4 years ago)

Improved patch delegating iter to self.forms

Line 
1diff --git a/django/forms/formsets.py b/django/forms/formsets.py
2index 6d92236..6a814d4 100644
3--- a/django/forms/formsets.py
4+++ b/django/forms/formsets.py
5@@ -48,6 +48,14 @@ class BaseFormSet(StrAndUnicode):
6 
7     def __unicode__(self):
8         return self.as_table()
9+   
10+    def __iter__(self):
11+        """Yields the forms in the order they should be rendered"""
12+        return iter(self.forms)
13+    def __getitem__(self, index):
14+        return list(self)[index]
15+    def __len__(self):
16+        return len(list(self))
17 
18     def _management_form(self):
19         """Returns the ManagementForm instance for this FormSet."""
20@@ -323,17 +331,17 @@ class BaseFormSet(StrAndUnicode):
21         # XXX: there is no semantic division between forms here, there
22         # probably should be. It might make sense to render each form as a
23         # table row with each field as a td.
24-        forms = u' '.join([form.as_table() for form in self.forms])
25+        forms = u' '.join([form.as_table() for form in self])
26         return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
27 
28     def as_p(self):
29         "Returns this formset rendered as HTML <p>s."
30-        forms = u' '.join([form.as_p() for form in self.forms])
31+        forms = u' '.join([form.as_p() for form in self])
32         return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
33 
34     def as_ul(self):
35         "Returns this formset rendered as HTML <li>s."
36-        forms = u' '.join([form.as_ul() for form in self.forms])
37+        forms = u' '.join([form.as_ul() for form in self])
38         return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
39 
40 def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,