Ticket #15950: callable-choice.diff

File callable-choice.diff, 1.4 KB (added by Jeremy Dunck, 14 years ago)
  • new file medley/abcs/fields.py

    diff --git a/medley/abcs/fields.py b/medley/abcs/fields.py
    new file mode 100644
    index 0000000..bc897b4
    - +  
     1import django
     2from django import forms
     3from django.utils.functional import SimpleLazyObject
     4
     5class 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
     13class 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
     28class CallableChoiceField(CallableChoicesMixin, forms.ChoiceField):
     29    pass
     30
     31class CallableMultipleChoiceField(CallableChoicesMixin, forms.MultipleChoiceField):
     32    pass
     33
     34class CallableTypedChoiceField(CallableChoicesMixin, forms.TypedChoiceField):
     35    pass
     36
     37# FIXME: remove conditional once 1.3 upgrade branch lands.
     38if django.VERSION >= (1, 3, 0):
     39    class CallableTypedMultipleChoiceField(CallableChoicesMixin, forms.TypedMultipleChoiceField):
     40        pass
Back to Top