From f073318668a40aab280a5e367e725e08538c52e3 Mon Sep 17 00:00:00 2001 From: Adrian Holovaty Date: Sun, 21 Jan 2007 01:10:55 +0000 Subject: [PATCH] newforms: Fixed confusing behavior when setting choices for ChoiceFields and their corresponding Widgets. Now, a Widget uses the choices from its ChoiceField regardless of whether the Widget has its own choices. git-svn-id: http://code.djangoproject.com/svn/django/trunk@4378 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/fields.py | 3 ++- tests/regressiontests/forms/tests.py | 36 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/django/newforms/fields.py b/django/newforms/fields.py index 2370d964a5..a72ac39d5c 100644 --- a/django/newforms/fields.py +++ b/django/newforms/fields.py @@ -319,7 +319,8 @@ class BooleanField(Field): class ChoiceField(Field): def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None): if isinstance(widget, type): - widget = widget(choices=choices) + widget = widget() + widget.choices = choices super(ChoiceField, self).__init__(required, widget, label, initial) self.choices = choices diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/tests.py index 336edf6cb7..b1425bef6d 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/tests.py @@ -1830,6 +1830,42 @@ For a form with a +You can specify widget attributes in the Widget constructor. +>>> class FrameworkForm(Form): +... name = CharField() +... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) +>>> f = FrameworkForm(auto_id=False) +>>> print f['language'] + +>>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) +>>> print f['language'] + + +When passing a custom widget instance to ChoiceField, note that setting +'choices' on the widget is meaningless. The widget will use the choices +defined on the Field, not the ones defined on the Widget. +>>> class FrameworkForm(Form): +... name = CharField() +... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'})) +>>> f = FrameworkForm(auto_id=False) +>>> print f['language'] + +>>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) +>>> print f['language'] + + Add widget=RadioSelect to use that widget with a ChoiceField. >>> class FrameworkForm(Form): ... name = CharField()