From 522f6740700f8bafae2845272e21da0074283809 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Wed, 15 Nov 2006 22:08:22 +0000 Subject: [PATCH] newforms: Implemented RadioSelect, with unit tests git-svn-id: http://code.djangoproject.com/svn/django/trunk@4072 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/widgets.py | 48 +++++++++++- tests/regressiontests/forms/tests.py | 111 +++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 4 deletions(-) diff --git a/django/newforms/widgets.py b/django/newforms/widgets.py index b24f91f4c6..c9b3d02913 100644 --- a/django/newforms/widgets.py +++ b/django/newforms/widgets.py @@ -5,7 +5,7 @@ HTML Widget classes __all__ = ( 'Widget', 'TextInput', 'PasswordInput', 'HiddenInput', 'FileInput', 'Textarea', 'CheckboxInput', - 'Select', 'SelectMultiple', + 'Select', 'SelectMultiple', 'RadioSelect', ) from django.utils.html import escape @@ -35,7 +35,10 @@ class Widget(object): return attrs class Input(Widget): - "Base class for all widgets (except type='checkbox', which is special)" + """ + Base class for all widgets (except type='checkbox' and + type='radio', which are special). + """ input_type = None # Subclasses must define this. def render(self, name, value, attrs=None): if value is None: value = '' @@ -102,8 +105,45 @@ class SelectMultiple(Widget): output.append(u'') return u'\n'.join(output) -class RadioSelect(Widget): - pass +class RadioInput(object): + "An object used by RadioFieldRenderer that represents a single ." + def __init__(self, name, value, attrs, choice): + self.name, self.value = name, value + self.attrs = attrs or {} + self.choice_value, self.choice_label = choice + + def __str__(self): + return u'' % (self.tag(), self.choice_label) + + def is_checked(self): + return self.value == str(self.choice_value) + + def tag(self): + final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) + if self.is_checked(): + final_attrs['checked'] = 'checked' + return u'' % flatatt(final_attrs) + +class RadioFieldRenderer(object): + "An object used by RadioSelect to enable customization of radio widgets." + def __init__(self, name, value, attrs, choices): + self.name, self.value, self.attrs = name, value, attrs + self.choices = choices + + def __iter__(self): + for choice in self.choices: + yield RadioInput(self.name, self.value, self.attrs, choice) + + def __str__(self): + "Outputs a