Permalink
Showing with 16 additions and 2 deletions.
  1. +1 −0 AUTHORS
  2. +3 −2 django/newforms/fields.py
  3. +12 −0 tests/regressiontests/forms/tests.py
View
1 AUTHORS
@@ -183,6 +183,7 @@ answer newbie questions, and generally made Django that much better:
Milton Waddams
wam-djangobug@wamber.net
Dan Watson <http://theidioteque.net/>
+ Chris Wesseling <Chris.Wesseling@cwi.nl>
Rachel Willmer <http://www.willmer.com/kb/>
Gary Wilson <gary.wilson@gmail.com>
wojtek
View
5 django/newforms/fields.py
@@ -339,8 +339,9 @@ def _get_choices(self):
def _set_choices(self, value):
# Setting choices also sets the choices on the widget.
- self._choices = value
- self.widget.choices = value
+ # choices can be any iterable, but we call list() on it because
+ # it will be consumed more than once.
+ self._choices = self.widget.choices = list(value)
choices = property(_get_choices, _set_choices)
View
12 tests/regressiontests/forms/tests.py
@@ -318,6 +318,7 @@
</select>
The 'choices' argument can be any iterable:
+>>> from itertools import chain
>>> def get_choices():
... for i in range(5):
... yield (i, i)
@@ -329,6 +330,17 @@
<option value="3">3</option>
<option value="4">4</option>
</select>
+>>> things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'})
+>>> class SomeForm(Form):
+... somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things]))
+>>> f = SomeForm()
+>>> f.as_table()
+u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>'
+>>> f.as_table()
+u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>'
+>>> f = SomeForm({'somechoice': 2})
+>>> f.as_table()
+u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>'
You can also pass 'choices' to the constructor:
>>> w = Select(choices=[(1, 1), (2, 2), (3, 3)])

0 comments on commit a52cc03

Please sign in to comment.