Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

newforms: Fixed confusing behavior when setting choices for ChoiceFie…

…lds 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
  • Loading branch information...
commit f073318668a40aab280a5e367e725e08538c52e3 1 parent c770803
Adrian Holovaty adrianholovaty authored
Showing with 38 additions and 1 deletion.
  1. +2 −1  django/newforms/fields.py
  2. +36 −0 tests/regressiontests/forms/tests.py
3  django/newforms/fields.py
View
@@ -319,7 +319,8 @@ def clean(self, value):
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
36 tests/regressiontests/forms/tests.py
View
@@ -1830,6 +1830,42 @@
<option value="J">Java</option>
</select>
+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']
+<select class="foo" name="language">
+<option value="P">Python</option>
+<option value="J">Java</option>
+</select>
+>>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
+>>> print f['language']
+<select class="foo" name="language">
+<option value="P" selected="selected">Python</option>
+<option value="J">Java</option>
+</select>
+
+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']
+<select class="foo" name="language">
+<option value="P">Python</option>
+<option value="J">Java</option>
+</select>
+>>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
+>>> print f['language']
+<select class="foo" name="language">
+<option value="P" selected="selected">Python</option>
+<option value="J">Java</option>
+</select>
+
Add widget=RadioSelect to use that widget with a ChoiceField.
>>> class FrameworkForm(Form):
... name = CharField()
Please sign in to comment.
Something went wrong with that request. Please try again.