0
0
Djangoframework~5 mins

DetailView for single objects in Django

Choose your learning style9 modes available
Introduction

A DetailView shows information about one specific item from your database. It helps you display details clearly without extra coding.

When you want to show details of a single blog post.
When displaying a user profile page.
When showing product details in an online store.
When you need to display information about one event or appointment.
Syntax
Django
from django.views.generic.detail import DetailView

class MyModelDetailView(DetailView):
    model = MyModel
    template_name = 'myapp/mymodel_detail.html'
    context_object_name = 'object'

# URL pattern example:
# path('mymodel/<int:pk>/', MyModelDetailView.as_view(), name='mymodel-detail')

model tells Django which database table to use.

template_name is the HTML file that shows the details.

Examples
This shows details for one Book object using a custom template and context name.
Django
class BookDetailView(DetailView):
    model = Book
    template_name = 'books/book_detail.html'
    context_object_name = 'book'
If you don't set template_name or context_object_name, Django uses defaults based on the model name.
Django
class UserProfileView(DetailView):
    model = User
    # Uses default template: user_detail.html
    # Uses default context name: 'user'
Sample Program

This example shows a Product model and a DetailView that displays one product's name and description. The URL uses the product's ID to find it.

Django
from django.db import models
from django.urls import path
from django.views.generic.detail import DetailView

# Model definition
class Product(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name

# DetailView for Product
class ProductDetailView(DetailView):
    model = Product
    template_name = 'product_detail.html'
    context_object_name = 'product'

# URL pattern
urlpatterns = [
    path('product/<int:pk>/', ProductDetailView.as_view(), name='product-detail'),
]

# Example product_detail.html template content:
# <h1>{{ product.name }}</h1>
# <p>{{ product.description }}</p>
OutputSuccess
Important Notes

The URL must include a primary key (pk) or slug to find the right object.

If the object is not found, Django shows a 404 error page automatically.

You can customize the template to show any fields you want from the object.

Summary

DetailView shows one object's details with little code.

Set the model and template to control what and how it shows.

Use URL patterns with pk or slug to select the object.