Kaydet (Commit) f0733186 authored tarafından Adrian Holovaty's avatar Adrian Holovaty

newforms: Fixed confusing behavior when setting choices for ChoiceFields and…

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
üst c770803f
......@@ -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
......
......@@ -1830,6 +1830,42 @@ For a form with a <select>, use ChoiceField:
<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()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment