๐Ÿ“ Django

Django DetailView

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
273
๐ŸŒฟ
Level
Medium

DetailView is a CBV for displaying a single object by its pk or slug.

Basic example

from django.views.generic import DetailView
from .models import Task

class TaskDetailView(DetailView):
    model = Task
    template_name = 'tasks/task_detail.html'
    context_object_name = 'task'

URL

path('tasks/<int:pk>/', views.TaskDetailView.as_view(), name='task-detail'),
# or by slug:
path('tasks/<slug:slug>/', views.TaskDetailView.as_view(), name='task-detail'),

Template

<h1>{{ task.title }}</h1>
<p>Status: {{ task.get_status_display }}</p>
<p>Owner: {{ task.owner.username }}</p>
<p>Created: {{ task.created_at|date:"d.m.Y" }}</p>

<a href="{% url 'task-edit' task.pk %}">Edit</a>
<a href="{% url 'task-delete' task.pk %}">Delete</a>

Additional context

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]
        return context

Access control

from django.contrib.auth.mixins import LoginRequiredMixin

class TaskDetailView(LoginRequiredMixin, DetailView):
    model = Task

    def get_queryset(self):
        return Task.objects.filter(owner=self.request.user)

Slug instead of pk

class TaskDetailView(DetailView):
    model = Task
    slug_field = 'slug'          # field on the model
    slug_url_kwarg = 'slug'      # parameter in the URL

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

๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐Ÿ“

CSRF Protection in Django

CSRF (Cross-Site Request Forgery) is an attack in which an adversary tricks the user's browser...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 294
๐Ÿ“

Django Migrations

A migration is a file describing changes to the database schema. Django tracks the state...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 286
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum