python – Django:按用户过滤ModelChoiceField

我有一个模型以及基于该模型的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))

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

编辑:添加我的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,说找不到请求.

最佳答案 您可以将request.user传递给视图中的init:

def some_view(request):
     form = TransactionForm(user=request.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
点赞