A Lazy ModelChoiceField implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class LazyModelChoiceField(forms.ChoiceField):
    '''
    A Lazy ModelChoiceField, similar to LazyChoiceField
    not overriding ModelChoiceField, since we need to convert the queryset into a tuple to sort it
    This allows for dynamic choices generation every time an instance of a Form is created.
    '''
    def __init__(self, *args, **kwargs):
	self.sort_by = kwargs.pop('sort_by', ())
	self.queryset = kwargs.pop('queryset', ())
	self.empty_label = kwargs.pop('empty_label', ())
        super(LazyModelChoiceField, self).__init__(*args, **kwargs)
        
    def __deepcopy__(self, memo):
        result = super(LazyModelChoiceField, self).__deepcopy__(memo)
        # requires of ugettext_lazy as _
        result.choices = ()
        for entry in self.queryset():
	    result.choices.append((entry.id, _(entry.__getattribute__(self.sort_by))))
	result.choices.sort(lambda x, y: cmp(x[1], y[1]))
        result.choices.insert(0, (0, self.empty_label))
	return result

More like this

  1. A Lazy ChoiceField implementation by lsbardel 4 years, 6 months ago
  2. ModelChoiceField with choice groups for recursive relationships by estecb 3 months ago
  3. Getting dynamic model choices in newforms by ubernostrum 7 years, 1 month ago
  4. CountryField (UN Country List, 3 Char Codes) by djm 5 years, 3 months ago
  5. Dictionary of choices based in models by marcoslhc 4 years ago

Comments

(Forgotten your password?)