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