Menu
CoddyTech

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 icon

Challenge

Easy

Make the home page list the real books.

  1. In books/views.py, give the template every book in the database as books, in place of the typed list.
  2. In home.html, show each book as its title and year in brackets, like Dune (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