A List from the Database
Part of the Models and the Admin section of Coddy's Django journey. Lesson 13 of 23.
The home page still lists three titles typed into the view. The view is where the page gets its data: it asks the ORM for rows and passes the QuerySet to the template, the way you passed a list before. A page of the books you have not read yet would be:
from django.shortcuts import render
from .models import Book
def to_read(request):
books = Book.objects.filter(is_read=False)
return render(request, "books/to_read.html", {"books": books})The dot in from .models means this app's own folder. In the template, each item of the loop is a Book, so {{ book.title }} and {{ book.price }} read its fields, and {{ book }} alone prints its __str__.
Challenge
EasyMake the home page list the real books.
- In
books/views.py, give the template every book in the database asbooks, in place of the typed list. - In
home.html, show each book as its title and year in brackets, likeDune (1965).
In the Shell tab, type Book.objects.create(title="Beloved", author="Toni Morrison", year=1987, price="13.00") and reload /: Beloved (1987) heads the list.
Try it yourself
from django.shortcuts import render
def home(request):
books = ["Dune", "Emma", "The Hobbit"]
return render(request, "books/home.html", {"books": books})
All lessons in Models and the Admin
Practice on your own: Django playground