Welcome to our Django tutorial series! Today, we're diving deep into the world of ListView. By the end of this tutorial, you'll have a solid understanding of how to display multiple records from a database in a web-friendly format.
ListView is a built-in generic view in Django that makes it easy to display a list of objects of a specified model. It handles pagination, sorting, and filtering for you, which is perfect for displaying a collection of data like blog posts, products, or users.
Using ListView saves you a ton of time. It takes care of the heavy lifting, allowing you to focus on the rest of your application. Plus, it's a great way to learn about Django's powerful and versatile generic views.
To follow along, make sure you have a Django project set up with an app containing a model. Let's use a simple Book model as an example:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
publication_year = models.IntegerField()
def __str__(self):
return self.titleTo create a ListView, you'll need to do the following:
Here's an example:
from django.views.generic.list import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'books/book_list.html'Now, create a new books/book_list.html template to define how the books will be displayed:
{% extends 'base.html' %}
{% block content %}
<h1>Book List</h1>
<ul>
{% for book in object_list %}
<li>
{{ book.title }} - {{ book.author }} - {{ book.publication_year }}
</li>
{% empty %}
<li>No books found.</li>
{% endfor %}
</ul>
{% endblock %}Make sure to create the base.html template as well, which will serve as the base template for all your views:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Head section -->
</head>
<body>
<div id="content" class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>Finally, add the new view to your project's URL patterns:
from django.urls import path
from .views import BookListView
urlpatterns = [
path('books/', BookListView.as_view(), name='book_list'),
]ListView offers many customization options, such as sorting, filtering, and pagination. We'll cover these in more detail in future tutorials.