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.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!