Ticket #3490: ChoiceField_iterable_choices_fix.patch

File ChoiceField_iterable_choices_fix.patch, 2.2 KB (added by Chris.Wesseling@…, 18 years ago)

Fixes ChoiceField(choices=( some generator )) bug.

  • django/newforms/fields.py

     
    339339
    340340    def _set_choices(self, value):
    341341        # Setting choices also sets the choices on the widget.
    342         self._choices = value
    343         self.widget.choices = value
     342        # And choices can be any iterable, but will be consumed more than once.
     343        self._choices = self.widget.choices = list(value)
    344344
    345345    choices = property(_get_choices, _set_choices)
    346346
  • tests/regressiontests/forms/tests.py

     
    314314<option value="4">4</option>
    315315</select>
    316316
     317Really, the 'choices' argument can be any iterable:
     318>>> from itertools import chain
     319>>> things = ({'id':1, 'name':'And Boom'}, {'id':2, 'name':'One More Thing!'})
     320>>> class SomeForm(Form):
     321...     somechoice = ChoiceField(choices=chain((('', '-'*9),), ( (thing['id'], thing['name']) for thing in things )))
     322>>> f = SomeForm()
     323>>> f.as_table()
     324u'<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>'
     325>>> f.as_table()
     326u'<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>'
     327
     328One More Thing:
     329>>> f = SomeForm({'somechoice': 2})
     330>>> f.as_table()
     331u'<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>'
     332
    317333You can also pass 'choices' to the constructor:
    318334>>> w = Select(choices=[(1, 1), (2, 2), (3, 3)])
    319335>>> print w.render('num', 2)
Back to Top