A Lazy ChoiceField implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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
        self._lazy_choices = kwargs.pop('choices',())
        super(LazyChoiceField,self).__init__(*args, **kwargs)
        
    def __deepcopy__(self, memo):
        result = super(LazyChoiceField,self).__deepcopy__(memo)
        result.choices = self._lazy_choices
        return result

More like this

  1. Dictionary of choices based in models by marcoslhc 3 years, 2 months ago
  2. Getting dynamic model choices in newforms by ubernostrum 6 years, 3 months ago
  3. Validation for full e-mails (e.g. "Joe Hacker <joe@hacker.com>") by akaihola 1 year, 6 months ago
  4. JSONField by deadwisdom 5 years, 10 months ago
  5. Dynamic tabular inlines with optional drag-n-drop sorting by Aneon 4 years, 1 month ago

Comments

(Forgotten your password?)