如何在Django中使用基于类的视图

时间:2019-04-08 11:44:52

标签: django

我想使用基于类的视图而不是基于函数的视图来显示模板。 如何将此代码更改为基于类的视图

  

views.py

 def homepage(request):
    categories = Category.objects.filter(active=True)
    products = Product.objects.filter(active=True).order_by('-created')
    featured_products = Product.objects.filter(featured=True)
    return render(request,'shop/base.html',{'categories':categories,'product':products,'featured_products':featured_products})

def categories(request,slug):
    category = Category.objects.get(slug=slug)
    products = Product.objects.filter(category=category,active=True)
    return render(request,'shop/products_list.html',{'products':products})

1 个答案:

答案 0 :(得分:1)

class HomePage(TemplateView):
    template_name = "base.html" 

    def get_context_data(self, **kwargs):
        context = super(HomePage, self).get_context_data(**kwargs)
        context['categories'] = Category.objects.filter(active=True)
        context['products'] = Product.objects.filter(active=True).order_by('-created')
        context['featured_products'] = Product.objects.filter(featured=True)
        return context

要添加通用视图所提供的信息以外的其他信息,您应该添加一个额外的上下文Documentation Here

查看此答案,了解如何将其他参数传递给基于类的视图Here