视图shop.views.product_list没有返回HttpResponse对象。它返回None

时间:2020-10-31 06:48:41

标签: python django django-views return httpresponse

这是我的代码,我一次又一次遇到相同的错误。我不知道这是怎么了。

category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if  category_slug:
    category = get_object_or_404(Category,  slug=category_slug)
    products = products.filter(category=category)
    return  render(request,'templates/shop/product/list.html',{'category':category,'categories':categories,'products':products})

1 个答案:

答案 0 :(得分:0)

这是因为返回位置。您每次都会返回,并且需要在此之前完成循环。 if 和 return 语句应该与此位于同一行/位置:

    category =None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    if category_slug:
        category=get_object_or_404(Category, 
                                    slug=category_slug)
        products = products.filter(category=category)
    return render(request, 'product/list.html',
                    {'category': category,
                    'categories':categories,
                    'products': products})