1
0
mirror of https://github.com/django/django.git synced 2025-10-30 00:56:09 +00:00

Fixed #13181 -- Added support for callable choices to forms.ChoiceField

Thanks vanschelven and expleo for the initial patch.
This commit is contained in:
Peter Inglesby
2014-10-27 20:21:59 +00:00
committed by Tim Graham
parent e0685368c6
commit 74e1980cf9
4 changed files with 50 additions and 5 deletions

View File

@@ -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)