[Django]-Django ModelMultipleChoiceField queryset/filter for objects already associated

0👍

woa this was asked 10 years ago..but prolly my idea might prove useful to developers who are will review this. I had a similar challenge.

the simple way is to comment out this:

#category=forms.ModelMultipleChoiceField(
#    Category.objects.filter(id__in=your_profile_instance.category.all()),
#    widget=forms.CheckboxSelectMultiple()
#)

lol and then below, after listing the fields add:

widgets = {
     'category': forms.CheckboxSelectMultiple,
    }

yea….

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

👤kevin

-1👍

As far as I know, the relation “category” can only be associated from a Profile instance (giving the associated categories), not from the class Profile itself. That’s why you get the error message.

If you substitute Profile in you example with the actual Profile instance (which I read is what you actually try to achieve) it would work better.

category=forms.ModelMultipleChoiceField(
    Category.objects.filter(id__in=your_profile_instance.category.all()),
    widget=forms.CheckboxSelectMultiple()
)

or just

category=forms.ModelMultipleChoiceField(
    queryset=your_profile_instance.category.all()),
    widget=forms.CheckboxSelectMultiple()
)

Have I understood your question correctly?

Leave a comment