From 08bec4fbc10ca5638ad22f20a753ec5e8d92eb0e Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Wed, 7 Dec 2011 23:08:27 +0000 Subject: Changed BoundField.subwidgets() to return SubWidget objects instead of rendered strings. This means we can access individual radio buttons' properties in the template (see new docs) git-svn-id: http://code.djangoproject.com/svn/django/trunk@17175 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/forms/forms.py | 8 +++++++- django/forms/widgets.py | 20 ++++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) (limited to 'django/forms') diff --git a/django/forms/forms.py b/django/forms/forms.py index 7818aac13a..d3f2046779 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -418,7 +418,13 @@ class BoundField(StrAndUnicode): iterate over individual radio buttons in a template. """ for subwidget in self.field.widget.subwidgets(self.html_name, self.value()): - yield self.as_widget(subwidget) + yield subwidget + + def __len__(self): + return len(list(self.__iter__())) + + def __getitem__(self, idx): + return list(self.__iter__())[idx] def _errors(self): """ diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 9c04750fdb..49b148eeca 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -137,6 +137,22 @@ class MediaDefiningClass(type): new_class.media = media_property(new_class) return new_class +class SubWidget(StrAndUnicode): + """ + Some widgets are made of multiple HTML elements -- namely, RadioSelect. + This is a class that represents the "inner" HTML element of a widget. + """ + def __init__(self, parent_widget, name, value, attrs, choices): + self.parent_widget = parent_widget + self.name, self.value = name, value + self.attrs, self.choices = attrs, choices + + def __unicode__(self): + args = [self.name, self.value, self.attrs] + if self.choices: + args.append(self.choices) + return self.parent_widget.render(*args) + class Widget(object): __metaclass__ = MediaDefiningClass is_hidden = False # Determines whether this corresponds to an . @@ -163,7 +179,7 @@ class Widget(object): Arguments are the same as for render(). """ - yield self + yield SubWidget(self, name, value, attrs, choices) def render(self, name, value, attrs=None): """ @@ -623,7 +639,7 @@ class SelectMultiple(Select): data_set = set([force_unicode(value) for value in data]) return data_set != initial_set -class RadioInput(StrAndUnicode): +class RadioInput(SubWidget): """ An object used by RadioFieldRenderer that represents a single . -- cgit v1.3