Add Extra Context with get_context_data

Extend template context in CBVs cleanly.


# models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=80)
  

# admin.py

from django.contrib import admin
from .models import Category

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ("name",)
  

# Result (views.py)
from django.views.generic import TemplateView
from .models import Category
class Home(TemplateView):
    template_name = "home.html"
    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx["categories"] = Category.objects.order_by("name")
        ctx["page_title"] = "Welcome"
        return ctx
  
Explanation:
  • Always call super() before adding keys.
  • Use get_context_data for per-view extras used by templates.
  • Category Views (FBV & CBV)
  • Total Views 661
  • Last Modified 15 December, 2025
  • Tags #cbv #context #views #templates
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.