From 74e1980cf96eb45079bef464fabdcbe0a6db2423 Mon Sep 17 00:00:00 2001 From: Peter Inglesby Date: Mon, 27 Oct 2014 20:21:59 +0000 Subject: Fixed #13181 -- Added support for callable choices to forms.ChoiceField Thanks vanschelven and expleo for the initial patch. --- django/forms/fields.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'django/forms') diff --git a/django/forms/fields.py b/django/forms/fields.py index 6403509fbb..81b3e2f4f9 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -798,6 +798,15 @@ class NullBooleanField(BooleanField): return initial != data +class CallableChoiceIterator(object): + def __init__(self, choices_func): + self.choices_func = choices_func + + def __iter__(self): + for e in self.choices_func(): + yield e + + class ChoiceField(Field): widget = Select default_error_messages = { @@ -822,7 +831,12 @@ class ChoiceField(Field): # Setting choices also sets the choices on the widget. # 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) + if callable(value): + value = CallableChoiceIterator(value) + else: + value = list(value) + + self._choices = self.widget.choices = value choices = property(_get_choices, _set_choices) -- cgit v1.3