在 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/
时,就能够显示从数据库中获取的书籍列表。