首页 文章

Django:按用户过滤ModelChoiceField

提问于
浏览
3

我有一个模型以及基于该模型的ModelForm . ModelForm包含一个ModelMultipleChoice字段,我在ModelForm的子类中指定:

class TransactionForm(ModelForm):

    class Meta:
        model = Transaction

    def __init__(self, *args, **kwargs):
        super(TransactionForm, self).__init__(*args, **kwargs)
        self.fields['category'] = forms.ModelChoiceField(queryset=Category.objects.filter(user=user))

如您所见,我需要按用户过滤Category queryset . 换句话说,用户应该只在下拉列表中看到自己的类别 . 但是,当用户,或者更具体地说,request.user在Model实例中不可用时,我该怎么做呢?

Edit: 添加我的CBV子类:

class TransUpdateView(UpdateView):
    form_class = TransactionForm
    model = Transaction
    template_name = 'trans_form.html'
    success_url='/view_trans/'

    def get_context_data(self, **kwargs):
        context = super(TransUpdateView, self).get_context_data(**kwargs)
        context['action'] = 'update'
        return context

我尝试了 form_class = TransactionForm(user=request.user) 并且我收到一个NameError,说没有找到请求 .

1 回答

  • 7

    您可以在视图中传递 request.user 以形成init:

    def some_view(request):
         form = TransactionForm(user=request.user)
    

    并添加 user 参数以形成 __init__ 方法(或从表单中的 kwargs 弹出):

    class TransactionForm(ModelForm):
        class Meta:
            model = Transaction
    
        # def __init__(self, *args, **kwargs):
            # user = kwargs.pop('user', User.objects.get(pk_of_default_user))
        def __init__(self, user, *args, **kwargs):
            super(TransactionForm, self).__init__(*args, **kwargs)
            self.fields['category'] = forms.ModelChoiceField(
                                         queryset=Category.objects.filter(user=user))
    

    update: 在基于类的视图中,您可以在 get_form_kwargs 中添加额外的参数以形成init:

    class TransUpdateView(UpdateView):
        #...
    
        def get_form_kwargs(self):
            kwargs = super(YourView, self).get_form_kwargs()
            kwargs.update({'user': self.request.user})
            return kwargs
    

相关问题