在 Django 中,可以通過以下步驟來實現數據庫網頁顯示:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publication_date = models.DateField()
def __str__(self):
return self.title
python manage.py makemigrations
python manage.py migrate
from django.shortcuts import render
from .models import Book
def book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books': books})
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} - {{ book.author }} - {{ book.publication_date }}</li>
{% endfor %}
</ul>
</body>
</html>
from django.urls import path
from .views import book_list
urlpatterns = [
path('books/', book_list, name='book_list'),
]
這樣,當訪問 http://localhost:8000/books/
時,就能夠顯示從數據庫中獲取的書籍列表。