Created
November 11, 2009 22:25
-
-
Save lsbardel/232372 to your computer and use it in GitHub Desktop.
Lazy ChoiceField for Django. This field will unwind choices only when a new instance of a Form is created.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LazyChoiceField(forms.ChoiceField): | |
''' | |
A Lazy ChoiceField. | |
This ChoiceField does not unwind choices until a deepcopy is called on it. | |
This allows for dynamic choices generation every time an instance of a Form is created. | |
''' | |
def __init__(self, *args, **kwargs): | |
# remove choices from kwargs. | |
# choices should be an iterable | |
self._lazy_choices = kwargs.pop('choices',()) | |
super(LazyChoiceField,self).__init__(*args, **kwargs) | |
def __deepcopy__(self, memo): | |
result = super(LazyChoiceField,self).__deepcopy__(memo) | |
lz = self._lazy_choices | |
if callable(lz): | |
lz = lz() | |
result.choices = lz | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment