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