Ticket #9230: forms.py.diff

File forms.py.diff, 1.9 KB (added by Reto Aebersold, 15 years ago)

Iterating over choice widgets

  • django/forms/forms.py

     
    362362        """
    363363        return self.form.errors.get(self.name, self.form.error_class())
    364364    errors = property(_errors)
    365 
    366     def as_widget(self, widget=None, attrs=None, only_initial=False):
     365   
     366    def prepare_widget_render(self, widget=None, attrs=None, only_initial=False):
    367367        """
    368         Renders the field by rendering the passed widget, adding any HTML
    369         attributes passed as attrs.  If no widget is specified, then the
    370         field's default widget will be used.
     368        Prepare the data needed for the widget rendering.
    371369        """
    372370        if not widget:
    373371            widget = self.field.widget
     
    388386            name = self.html_name
    389387        else:
    390388            name = self.html_initial_name
     389           
     390        return widget, name, data, attrs
     391
     392    def as_widget(self, widget=None, attrs=None, only_initial=False):
     393        """
     394        Renders the field by rendering the passed widget, adding any HTML
     395        attributes passed as attrs.  If no widget is specified, then the
     396        field's default widget will be used.
     397        """
     398        widget, name, data, attrs = self.prepare_widget_render(widget, attrs, only_initial)
    391399        return widget.render(name, data, attrs=attrs)
     400   
     401    def __iter__(self):
     402        """
     403        Check if current widget is iteratable and return the widget iterator.
     404        """
     405        widget, name, data, attrs = self.prepare_widget_render()
     406        if not hasattr(widget, 'get_iterator'):
     407            raise Exception, "Can not iterate over widget '%s'" % widget.__class__.__name__
     408        return widget.get_iterator(name, data, attrs=attrs)
    392409
    393410    def as_text(self, attrs=None, **kwargs):
    394411        """
Back to Top