Building catalog views

In order to display the product catalog, we need to create a view to list all the products or filter products by a given category. Edit the views.py file of the shop application and add the following code to it:

from django.shortcuts import render, get_object_or_404from .models import Category, Productdef product_list(request, category_slug=None):    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,                  'shop/product/list.html',                  {'category': category,                   'categories': categories,                   'products': products})

We will filter the QuerySet with ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.