Skip to content Skip to sidebar Skip to footer

Django Form: Only Show Manytomany Objects From Logged In User

The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created. Something like this

Solution 1:

Since you're using a ModelForm, the associated_protfolios field will be a ModelMultipleChoiceField [docs]. This field has a queryset attribute [docs]. We want to modify that attribute.

Django's CreateView has a method get_form, which in this case will grab your PostCreateForm. This is a good spot to filter the field's queryset, since we have access to the user:

classPostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    defget_form(self, *args, **kwargs):
        form = super().get_form(*args, **kwargs)  # Get the form as usual
        user = self.request.user
        form.fileds['associated_portfolios'].queryset = Portfolio.objects.filter(user=user)
        return form

Solution 2:

Did you try this

self.fields['associated_portfolios'] = Post.objects.filter(associated_portfolios__portfolio__user=request.user)

OR

user_posts = Post.objects.filter(user=request.user)
self.fields['associated_portfolios'] = user_posts.associated_portfolios.all()

read more about M2M relationships querying here, because I think your problem may be with it.

Also, I'm not sure about your actual data maybe it's right and it gives a correct result as filtering Portfolio model against current user to get its objects looks right for me, but anyway double check everything again.

And as a final note, add related_name to your model fields so you can use it easily for reverse relations rather than going with Django's default naming, it will be clearer and give a better understanding.

Post a Comment for "Django Form: Only Show Manytomany Objects From Logged In User"