0
0
Djangoframework~30 mins

ListView for displaying collections in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
ListView for displaying collections
📖 Scenario: You are building a simple web app to show a list of books in a library. You want to display all books on a page using Django's built-in ListView to make it easy and clean.
🎯 Goal: Create a Django ListView to display a list of books from a model called Book. You will set up the model, configure the view, and connect it to a template to show the book titles.
📋 What You'll Learn
Create a Book model with a title field
Create a BookListView using Django's ListView
Set the view to use the Book model and a template named book_list.html
Add the URL pattern to connect the view to the path /books/
Create a simple template to display all book titles in an unordered list
💡 Why This Matters
🌍 Real World
Displaying lists of items like products, articles, or users is common in web apps. Django's ListView makes this easy and clean.
💼 Career
Understanding Django's generic views and templates is essential for backend web development jobs using Django.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with a single field title that is a CharField with max length 100.
Django
Need a hint?

Use models.CharField(max_length=100) for the title field inside the Book model.

2
Create the BookListView
Create a Django class-based view called BookListView that inherits from ListView. Set its model attribute to Book and template_name to 'book_list.html'.
Django
Need a hint?

Import ListView from django.views.generic and set the model and template_name attributes in your view.

3
Add URL pattern for BookListView
In your Django app's urls.py, import BookListView and add a URL pattern that maps the path 'books/' to BookListView.as_view(). Name this URL pattern 'book-list'.
Django
Need a hint?

Use path('books/', BookListView.as_view(), name='book-list') inside urlpatterns.

4
Create the book_list.html template
Create a Django template named book_list.html that loops over the object_list context variable and displays each book's title inside an unordered list (<ul>).
Django
Need a hint?

Use a {% for book in object_list %} loop and display {{ book.title }} inside <li> tags.