Views in Python

From the Django cheat sheet · Views & URLs · verified Jul 2026

Views

Function and class-based views

python
from django.shortcuts import render, get_object_or_404

def product_list(request):
    products = Product.objects.all()
    return render(request, 'products/list.html', {'products': products})

# Class-based view
from django.views.generic import ListView

class ProductListView(ListView):
    model = Product
    template_name = 'products/list.html'
💡 Use CBV for standard CRUD operations
📌 LoginRequiredMixin for auth protection
⚡ Override get_queryset() for filtering
🟢 Function views are simpler for custom logic

More Python tasks

Back to the full Django cheat sheet