对象没有属性“ object_list”

时间:2020-08-03 20:16:13

标签: python python-3.x django django-views

我遇到了错误,我认为可能是出于同样的原因,Viktor遇到了问题('ProductList' object has no attribute 'object_list'

AKS在Viktors帖子上写道-

您可能在超类的get_context_data()的以下行上收到错误:

queryset = kwargs.pop('object_list', self.object_list)

BaseListView的get方法通过调用object_list方法在视图上设置get_queryset

self.object_list = self.get_queryset()

但是,对于您而言,您是在get_context_data()方法本身中调用get_queryset,并且此时未在视图上设置object_list

我回顾了我的踪迹,看到了AKS提到的代码。

  File "C:\Users\HP\Django Projects\EcommerceProject\products\views.py", line 48, in get_context_data
    context = super(ProductListView, self).get_context_data(*args, **kwargs)
  File "c:\Users\HP\DJANGO~1\ECOMME~1\lib\site-packages\django\views\generic\list.py", line 131, in get_context_data
    queryset = kwargs.pop('object_list', self.object_list)
AttributeError: 'ProductListView' object has no attribute 'object_list'
[03/Aug/2020 18:20:21] "GET /products/ HTTP/1.1" 500 90906

这是我的代码

class ProductListView(ListView):
    model = Product
    template_name = "products/list.html"
    # added for pagination
    context_object_name='object_list' #Default: object_list
    # print(context_object_name)
    # paginate_by = 3

def get_context_data(self, *args, **kwargs):
    context = super(ProductListView, self).get_context_data(*args, **kwargs)
    cart_obj, new_obj = Cart.objects.new_or_get(self.request)
    print("get context data")
    # context = {}
    context['cart'] = cart_obj
    return context



def get_queryset(self, *args, **kwargs):
    request = self.request
    return Product.objects.all()

def get(self, request):
    
    paginate_by = request.GET.get('paginate_by',6) or 4
    data = self.model.objects.all()
    paginator = Paginator(data, paginate_by)
    page = request.GET.get('page')
   
    try:
        paginated = paginator.page(page)
    except PageNotAnInteger:
        paginated = paginator.page(1)
    except EmptyPage:
        paginated = paginator.page(paginator.num_pages)

    # context={}
    context = self.get_context_data()
    context['DataPaginated'] = paginated
    context['paginate_by'] = paginate_by

    # return render(request, self.template_name, {'DataPaginated':paginated, 'paginate_by':paginate_by, 'cart':cart_obj})
    return render(request, self.template_name, context)

问题已解决

我在类get_context_data中修改了ProductListView(ListView):函数

def get_context_data(self, *args, **kwargs):
    self.object_list = super().get_queryset()
    context = super(ProductListView, self).get_context_data(*args, **kwargs)
    

1 个答案:

答案 0 :(得分:0)

您要解决的确切问题是什么?或者通过代码要解决的问题到底是什么?

您要设置上下文对象名称还是要从产品模型中检索数据?

如果要从产品模型中检索数据,则只需使用objects.filter。

如果此行:context = super(ProductListView, self).get_context_data(*args, **kwargs)是您要解决的问题,请尝试将def get_context_data移动到ProductListView类中。