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

我们两清 提交于 2019-12-07 21:52:03

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/16137736/django-filter-the-set-presented-in-a-many-to-many-modelform-by-currently-logged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!