DetailView
Show a single object looked up from the URL.
Syntax
class PostDetailView(DetailView): model = PostDetailView displays one object. It reads a primary key (pk) or slug from the URL, fetches the record and passes it to the template as object.
The default template name is <app>/<model>_detail.html.
Example
from django.views.generic import DetailView
from .models import Post
class PostDetailView(DetailView):
model = Post
context_object_name = "post"
# blog/urls.py
# path("post/<int:pk>/", PostDetailView.as_view(), name="detail")When to use it
- A developer uses DetailView to display a single blog post page, automatically looking up the record by its pk.
- A developer overrides get_object() in a DetailView to look up by slug instead of the default pk.
- A team uses DetailView's automatic 404 behavior to return a not-found page when a record doesn't exist.
More examples
Basic DetailView
Looks up a Post by pk from the URL and passes it to the template as 'post'.
from django.views.generic import DetailView
from .models import Post
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html"
context_object_name = "post"Look up by slug
Configures DetailView to look up the Post by a slug field instead of the default pk.
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html"
slug_field = "slug"
slug_url_kwarg = "slug"
# urls.py:
# path('<slug:slug>/', PostDetailView.as_view(), name='post-detail')Extra context in DetailView
Adds the post's approved comments to the template context alongside the post object.
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["comments"] = self.object.comments.filter(approved=True)
return context
Discussion