| 1 | import django |
| 2 | from django import forms |
| 3 | from django.utils.functional import SimpleLazyObject |
| 4 | |
| 5 | class SimpleLazyList(SimpleLazyObject): |
| 6 | def __iter__(self): |
| 7 | if self._wrapped is None: self._setup() |
| 8 | return iter(self._wrapped) |
| 9 | |
| 10 | def _setup(self): |
| 11 | self._wrapped = list(self._setupfunc()) |
| 12 | |
| 13 | class CallableChoicesMixin(object): |
| 14 | """ A ChoiceField that can take a callable |
| 15 | """ |
| 16 | def _get_choices(self): |
| 17 | return self._choices |
| 18 | |
| 19 | def _set_choices(self, value): |
| 20 | if callable(value): |
| 21 | list_value = SimpleLazyList(value) |
| 22 | else: |
| 23 | list_value = list(value) |
| 24 | self._choices = self.widget.choices = list_value |
| 25 | |
| 26 | choices = property(_get_choices, _set_choices) |
| 27 | |
| 28 | class CallableChoiceField(CallableChoicesMixin, forms.ChoiceField): |
| 29 | pass |
| 30 | |
| 31 | class CallableMultipleChoiceField(CallableChoicesMixin, forms.MultipleChoiceField): |
| 32 | pass |
| 33 | |
| 34 | class CallableTypedChoiceField(CallableChoicesMixin, forms.TypedChoiceField): |
| 35 | pass |
| 36 | |
| 37 | # FIXME: remove conditional once 1.3 upgrade branch lands. |
| 38 | if django.VERSION >= (1, 3, 0): |
| 39 | class CallableTypedMultipleChoiceField(CallableChoicesMixin, forms.TypedMultipleChoiceField): |
| 40 | pass |