0
0
Djangoframework~30 mins

DetailView for single objects in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
DetailView for Single Objects in Django
📖 Scenario: You are building a simple Django web app to show details of books in a library. Each book has a title, author, and description. You want to create a page that shows the details of one book when a user visits its URL.
🎯 Goal: Build a Django DetailView to display information about a single book object.
📋 What You'll Learn
Create a Django model called Book with fields title, author, and description.
Create a URL pattern to access a book detail page by its pk.
Create a Django DetailView class called BookDetailView to show one book.
Create a simple HTML template to display the book's title, author, and description.
💡 Why This Matters
🌍 Real World
Detail views are common in websites to show full information about one item, like a product page or user profile.
💼 Career
Understanding Django's DetailView is essential for backend web development jobs using Django framework.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book in models.py with these exact fields: title as CharField(max_length=100), author as CharField(max_length=100), and description as TextField().
Django
Need a hint?

Use models.CharField for short text and models.TextField for longer text.

2
Add URL pattern for Book detail
In urls.py, import BookDetailView and add a URL pattern with path 'books/<int:pk>/' that uses BookDetailView.as_view() and name it 'book-detail'.
Django
Need a hint?

Use path with <int:pk> to capture the book's primary key.

3
Create the BookDetailView class
In views.py, import DetailView from django.views.generic and Book model. Create a class called BookDetailView that inherits from DetailView. Set its model attribute to Book.
Django
Need a hint?

Set the model attribute inside your BookDetailView class.

4
Create the template for BookDetailView
Create a template file named book_detail.html inside your app's templates folder. Use the object context variable to display the book's title, author, and description inside appropriate HTML tags.
Django
Need a hint?

Use double curly braces {{ }} to show object fields in the template.