[英]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? 最好的方法是什么?
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. 因此,您需要覆盖表单的
__init__
,将当前用户传递给该表单。 And then set a queryset
attribute on the ManyToManyField you want. 然后在所需的ManyToManyField上设置一个
queryset
属性。
Your view: 您的看法:
#GET request
book_form = BookForm(user=request.user)
#POST request
book_form = BookForm(data=request.POST, user=request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.