且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django表单:仅显示已登录用户的许多对象

更新时间:2023-12-01 16:01:22

由于您使用的是 ModelForm ,因此 associated_protfolios 字段将是 ModelMultipleChoiceField [ docs ].此字段具有 queryset 属性[文档].我们要修改该属性.

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的 CreateView 具有方法 get_form ,在这种情况下,它将获取您的 PostCreateForm .这是过滤字段的查询集的好地方,因为我们可以访问用户:

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:

class PostCreate(CreateView):
    model = Post
    form_class = PostCreateForm

    def get_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