Ticket #13181: patch.diff

File patch.diff, 1.6 KB (added by mariarchi, 15 years ago)
  • django/forms/fields.py

     
    597597        # Setting choices also sets the choices on the widget.
    598598        # choices can be any iterable, but we call list() on it because
    599599        # it will be consumed more than once.
    600         self._choices = self.widget.choices = list(value)
     600        if callable(value):
     601            value = value()
     602        value = list(value)
     603        self._choices = self.widget.choices = value
    601604
    602605    choices = property(_get_choices, _set_choices)
    603606
  • tests/regressiontests/forms/fields.py

     
    625625        self.assertEqual(u'5', f.clean('5'))
    626626        self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, '6')
    627627
     628    def test_choicefield_callable(self):
     629        choices = lambda: [('J', 'John'), ('P', 'Paul')]
     630        f = ChoiceField(choices=choices)
     631        self.assertEqual(u'J', f.clean('J'))
     632       
     633    def test_choicefield_callable_2(self):
     634        choices = lambda: 1
     635        self.assertRaisesErrorWithMessage(TypeError, "'int' object is not iterable", ChoiceField, choices=choices)
    628636    # TypedChoiceField ############################################################
    629637    # TypedChoiceField is just like ChoiceField, except that coerced types will
    630638    # be returned:
Back to Top