Login

A Lazy ChoiceField implementation

Author:
lsbardel
Posted:
October 20, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

Sometimes it is useful to have a ChoiceField which calculates its choices at runtime, when a new instance of a form containing it, is generated. And this is what LazyChoiceField does. The choices argument must be an iterable as for ChoiceField.

Usage example

from django import forms

DynamicApplicationList = []

class MyForm(forms.Form):
    dynamic_choice = LazyChoiceField(choices = DynamicApplicationList)

DynamicApplicationList can now be updated dynamically.

 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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.