How to group by an objects category field using ModelMultipleChoiceField with widget CheckboxSelectMultiple?

In a forms.Form I have:

 objects = forms.ModelMultipleChoiceField(
     queryset=Object.objects.all(),
     widget=forms.CheckboxSelectMultiple)

Is it possible to access this objects category field in a template loop for checkboxes, to be able to sort them according to which category they belong? Or in any other way.

If not and one has to create a custom widget or field, is that possible to do with a couple of lines and not 70+ like I have seen in other suggested solutions elsewhere?

Thanks for your time and help, it is appreciated.

Now I have the solution below, making the fields dynamic instead. Is this an acceptable solution, or are there better ways? Perhaps a more efficient one? (This is filtering on two types of categories on the same object, first one then a second, which is the one relevant when displaying the checkboxes but not for my initial question)

The form constructor:

    objects = Object.objects.filter(object_category__name=category)
    categories = set()

    for object in objects:
        categories.add(object.second_category)

    for category in categories:
        query = objects.filter(second_category__pk=category.pk)
        field_name = f"category_{category.pk}"
        self.fields[field_name] = forms.ModelMultipleChoiceField(
                    queryset=query,
                    widget=forms.CheckboxSelectMultiple,
                    label=category.name)

Technically, if it works, it’s “acceptable”.

In this case, yes, this is a good solution for adding dynamic fields to the form.

(I might think about using the ORM to create the categories using distinct instead of iterating over all the elements myself, but since I’m assuming we’re talking about less than 100 elements in Object, it probably doesn’t really matter.)

1 Like