加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django:按用户过滤ModelChoiceField

发布时间:2020-12-20 11:32:48 所属栏目:Python 来源:网络整理
导读:我有一个模型以及基于该模型的ModelForm. ModelForm包含一个ModelMultipleChoice字段,我在ModelForm的子类中指定: class TransactionForm(ModelForm): class Meta: model = Transaction def __init__(self,*args,**kwargs): super(TransactionForm,self).__
我有一个模型以及基于该模型的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,**kwargs):
        # user = kwargs.pop('user',User.objects.get(pk_of_default_user))
    def __init__(self,user,**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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读