Skip to content

Instantly share code, notes, and snippets.

@lsbardel
Created November 11, 2009 22:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lsbardel/232372 to your computer and use it in GitHub Desktop.
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.
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