You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django多继承FormView与ListView报AttributeError问题解决

Django POST请求报错:AttributeError: Worker object has no attribute 'object_list'

我自定义了名为AccessCheck的Mixin,还实现了继承AccessCheck、FormView和ListView的ListFormView视图,用于展示Worker对象列表并实现创建/更新操作。但通过POST方法添加新数据时,Django持续返回**AttributeError: Worker object has no attribute 'object_list'**错误。更困惑的是,该ListFormView是从另一应用中正常运行的类视图复制而来,我反复检查代码仍未找到问题根源。

AccessCheck Mixin 代码

class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View):
    def test_func(self, *args, **kwargs):
        access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])]
        return self.request.user.is_superuser or selr.request.user.id in access

    def handle_no_permission(self):
        return redirect('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id'])
        return context

ListFormView(原代码)

class ListFormView(AccessCheck, FormView, ListView):
    template_name = 'my_template_name.html'
    context_object_name = 'workers'
    form_class = WorkerForm
    success_url = './my_url'

    def form_valid(self, form):
        data = form.save()
        return super().form_valid(form)

    def get_queryset(self, *args, **kwargs):
        return Worker.objects.filter(shop_id = self.kwargs['shop_id'])

解决方法

在ListFormView的get_context_data方法中手动设置self.object_list,修改后的代码如下:

ListFormView(修改后)

class ListFormView(AccessCheck, FormView, ListView):
    template_name = 'my_template_name.html'
    context_object_name = 'workers'
    form_class = WorkerForm
    success_url = './my_url'

    def get_context_data(self, **kwargs):
        self.object_list = Worker.objects.filter(shop_id = self.kwargs['shop_id'])
        context = super().get_context_data(**kwargs)
        return context

    def form_valid(self, form):
        data = form.save()
        return super().form_valid(form)

    def get_queryset(self, *args, **kwargs):
        return Worker.objects.filter(shop_id = self.kwargs['shop_id'])

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:35:15