-3

I want to use class based views instead of function based views to display the template. How to change this code into class based views

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 Answers1

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

To add some extra information beyond that provided by a generic view you should add an extra context Documentation Here

Checkout this answer on how to pass additional parameters to a class based view Here

Jeffrey Chidi
  • 341
  • 3
  • 14