4

I have a Profile object with manytomany relationship to Category


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

In my form, I want to display a checkbox of only the categories associated with the Profile The code below will display all categories.


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

How do i write a queryset so that I show only the categories associated with the Profile? I've variations of this:


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

Has this error: 'ReverseManyRelatedObjectsDescriptor' object has no attribute 'all'

Larry Mai
  • 53
  • 1
  • 6
  • Nevermind: I have to define the queryset in the view. I gues sit has to do with run time variable form.fields["category"].queryset = Category.objects.filter(profile=profile) – Larry Mai Dec 02 '10 at 20:47

2 Answers2

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
  • and the in the views u can filter like: https://stackoverflow.com/questions/60259091/django-form-only-show-manytomany-objects-from-logged-in-user – kevin Jan 29 '21 at 10:31
-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?

pereric
  • 109
  • 3