Program 3
Title: View a List of Books with Titles and Authors Using Django
Aim:
To develop a Django application to view a list of books with titles and authors and
display them using the admin interface and a web page.
Software/Hardware Requirements:
• Python 3.x
• Django 4.x or later
• Web Browser
• Text Editor/IDE (VS Code, PyCharm, etc.)
Procedure:
Step 1: Project Setup
Open terminal and type:
django-admin startproject bookproject
cd bookproject
python [Link] startapp books
Step 2: Register the App
In bookproject/[Link], add:
INSTALLED_APPS = [
...
'books',
]
Step 3: Create Book Model
In books/[Link]:
from [Link] import models
class Book([Link]):
title = [Link](max_length=200)
author = [Link](max_length=200)
def __str__(self):
return [Link]
Step 4: Register Model in Admin
In books/[Link]:
from [Link] import admin
from .models import Book
[Link](Book)
Step 5: Migrate Database
Run the following commands:
python [Link] makemigrations
python [Link] migrate
Step 6: Create Superuser
Run the following command:
python [Link] createsuperuser
Provide username, email, and password when prompted.
Step 7: Run the Server
Run the following command:
python [Link] runserver
Visit: [Link] to login and add books.
Step 8: Display Books on Web Page
URL Configuration:
In bookproject/[Link]:
from [Link] import admin
from [Link] import path
from books import views
urlpatterns = [
path('admin/', [Link]),
path('books/', views.book_list, name='book_list'),
]
View Function:
In books/[Link]:
from [Link] import render
from .models import Book
def book_list(request):
books = [Link]()
return render(request, 'books/book_list.html', {'books': books})
Create Template:
Make a folder templates/books/ inside the books app, then create book_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>List of Books</h1>
<ul>
{% for book in books %}
<li>{{ [Link] }} by {{ [Link] }}</li>
{% endfor %}
</ul>
</body>
</html>
Output:
• Visit [Link] to view the list of books.
• Visit [Link] to manage books.
Result:
The Django application was successfully developed to view a list of books using the
admin interface and display them on a web page.