Django ModelMultipleChoiceField queryset / filter for already associated objects

I have a Profile object with manytomany category relation


class Profile(models.Model):
    . . . 
    category = models.ManyToManyField(Category, blank=True)

In my form, I want to display a checkmark only for categories related to the profile. In the code below, all categories will be displayed.


class ProfileForm(ModelForm):
    . . .
    category = forms.ModelMultipleChoiceField(Category.objects.all(),
                  widget=forms.CheckboxSelectMultiple())

How do I write a request so that I only show categories related to a profile? I have options for this:


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

Does this error occur: the "ReverseManyRelatedObjectsDescriptor" object does not have an "all" attribute

+3
source share
1 answer

, "" ( ), . .

Profile (, , ), .

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

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

?

0

Source: https://habr.com/ru/post/1778183/


All Articles