[Answered ]-Access many-to-many relations of foreign object as multiple choice in model form

1👍

Thanks to @WillemVanOnsem, I figured out the answer.

The solution is to use a ModelMultipleChoiceField with queryset to provide the options – all users in my example. Overwriting __init()__ then allows to pass the initial data, i.e. the users in the group, by accessing the model’s instance – here LectureClass.group.user_set.all().

class LectureClassForm(forms.ModelForm):
    members = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(),
        widget=forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
        super(LectureClassForm, self).__init__(*args, **kwargs)
        self.initial["members"] = self.instance.group.user_set.all()
        pass

    def save(self, commit=True):
        instance = super(LectureClassForm, self).save()
        self.instance.group.user_set.set(self.cleaned_data["members"])
        return instance

    class Meta:
        model = LectureClass
        fields = ["name", "is_invitation_code_active"]

Leave a comment