Bastian
Bastian

Reputation: 5855

Django, Filter the set presented in a many to many modelform by currently logged in user

I know it's there somewhere but I can't find it.

So I have a 'category' model and a 'book' model which has a many to many to 'category'. When creating a new book in a modelform, all the categories are presented to the user to assign to the book. In that case I want only the categories created by the current user to show up in that field, not all the categories.

What's the best approach?

Upvotes: 3

Views: 2157

Answers (1)

Akshar Raaj
Akshar Raaj

Reputation: 15211

Assuming your model like:

class Category(models.Model):
    ....
    creator = models.ForeignKey(User)

class Book(models.Model):
    ...
    categories = models.ManyToManyField(Category)

Assuming your form like:

class BookForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        current_user = kwargs.pop('user')
        super(BookForm, self).__init__(*args, **kwargs)
        self.fields['categories'].queryset = Categories.objects.filter(creator=current_user)

So, you need to overide __init__ of your form, pass the current user to this form. And then set a queryset attribute on the ManyToManyField you want.

Your view:

#GET request
book_form = BookForm(user=request.user)

#POST request
book_form = BookForm(data=request.POST, user=request.user)

Upvotes: 7

Related Questions