Hello Guys,
I have a form with a ModelMultipleChoiceField
to list of categories.
I would like to group categories using the Category.group
field.
I thought that by changing the field.choices
in the init function it will make the trick
class CategoriesField(forms.ModelMultipleChoiceField):
def __init__(self, queryset, **kwargs):
super(forms.ModelMultipleChoiceField, self).__init__(queryset, **kwargs)
self.queryset = queryset.select_related()
self.to_field_name=None
group = None
list = []
self.choices = []
for category in queryset:
if not group:
group = category.group
if group != category.group:
self.choices.append((group.title, list))
group = category.group
list = [(category.id, category.name)]
else:
list.append((category.id, category.name))
try:
self.choices.append((group.title, list))
except:
pass
But the ModelChoiceIterator
still erase the self.choices
info that are set in the __init__
function.
How can I do that the right way ?