📝 Django

Django DetailView

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
73
🌿
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

📝

pytest-django: Testing Django

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

📅 30.06.2026 👁️ 138
📝

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

📅 30.06.2026 👁️ 101
📝

RAG: Chatting with Documents via Vector Search

RAG (Retrieval-Augmented Generation) is a pattern for working with your own documents. Instead of fine-tuning...

📅 30.06.2026 👁️ 94

Did you like the article?

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