Ticket #14655: formset-iterable.diff

File formset-iterable.diff, 1.9 KB (added by kenth, 14 years ago)
  • django/forms/formsets.py

    diff --git a/django/forms/formsets.py b/django/forms/formsets.py
    index 62a25bf..4af3b6d 100644
    a b class BaseFormSet(StrAndUnicode):  
    4848
    4949    def __unicode__(self):
    5050        return self.as_table()
     51   
     52    def __iter__(self):
     53        """Yields the forms in the order they should be rendered"""
     54        for form in self.forms:
     55            yield form
     56   
     57    def __getitem__(self, index):
     58        try:
     59            return list(self)[index]
     60        except IndexError:
     61            raise IndexError('Index %d out of range for formset' % index)
     62       
     63    def __len__(self):
     64        return sum(1 for _ in self)
    5165
    5266    def _management_form(self):
    5367        """Returns the ManagementForm instance for this FormSet."""
    class BaseFormSet(StrAndUnicode):  
    323337        # XXX: there is no semantic division between forms here, there
    324338        # probably should be. It might make sense to render each form as a
    325339        # table row with each field as a td.
    326         forms = u' '.join([form.as_table() for form in self.forms])
     340        forms = u' '.join([form.as_table() for form in self])
    327341        return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
    328342
    329343    def as_p(self):
    330344        "Returns this formset rendered as HTML <p>s."
    331         forms = u' '.join([form.as_p() for form in self.forms])
     345        forms = u' '.join([form.as_p() for form in self])
    332346        return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
    333347
    334348    def as_ul(self):
    335349        "Returns this formset rendered as HTML <li>s."
    336         forms = u' '.join([form.as_ul() for form in self.forms])
     350        forms = u' '.join([form.as_ul() for form in self])
    337351        return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
    338352
    339353def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
Back to Top