📝 Django

get_context_data in Django CBVs

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
85
🌿
Level
Medium

get_context_data() is a CBV method for passing additional data to a template.

Basic usage

from django.views.generic import ListView
from .models import Task, Project

class TaskListView(ListView):
    model = Task
    template_name = 'tasks/task_list.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['projects'] = Project.objects.all()
        context['total_count'] = Task.objects.count()
        context['page_title'] = 'All tasks'
        return context

In the template

<h1>{{ page_title }}</h1>
<p>Total tasks: {{ total_count }}</p>

<select name="project">
  {% for project in projects %}
    <option value="{{ project.pk }}">{{ project.name }}</option>
  {% endfor %}
</select>

DetailView + additional data

class TaskDetailView(DetailView):
    model = Task

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['related_tasks'] = Task.objects.filter(
            project=self.object.project
        ).exclude(pk=self.object.pk)[:5]
        context['can_edit'] = self.object.owner == self.request.user
        return context

Data from the request

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['search_query'] = self.request.GET.get('q', '')
    context['active_filter'] = self.request.GET.get('status', 'all')
    return context

Important: always call super()

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)  # base context (object_list, etc.)
    context['extra'] = 'value'
    return context

Without super() you will lose object_list, object, view, and other standard template variables.

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 133
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 85
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 73

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!