Login

A Lazy ModelChoiceField implementation

Author:
alecdotico
Posted:
July 16, 2013
Language:
Python
Version:
1.5
Score:
0 (after 0 ratings)

Sometimes we may need to generate a ModelChoiceField in which choices are generated at runtime, depending on the locale language. The snippet generates a ChoiceField based on a queryset and a specific attribute of the Model, ordering the choices by the attribute content in the locale language.

Usage example (inside a form declaration)

country = LazyModelChoiceField(sort_by='name', queryset = \
Country.objects.all, empty_label=_('All countries'), label=_('Country'))

Based on lsbardel LazyChoiceField implementation (snippet 1767)

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

Comments

Please login first before commenting.