溫馨提示×

django怎么實現(xiàn)數(shù)據(jù)庫網(wǎng)頁顯示

小億
121
2024-01-13 18:48:11
欄目: 編程語言

在 Django 中,可以通過以下步驟來實現(xiàn)數(shù)據(jù)庫網(wǎng)頁顯示:

  1. 定義模型類:首先,需要在 Django 的 models.py 文件中定義模型類,以描述數(shù)據(jù)庫中的表結構和字段屬性。
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
  1. 遷移數(shù)據(jù)庫:運行以下命令來進行數(shù)據(jù)庫遷移,以創(chuàng)建相應的表結構。
python manage.py makemigrations
python manage.py migrate
  1. 創(chuàng)建視圖函數(shù):在 views.py 文件中創(chuàng)建視圖函數(shù),用于處理對應的請求,并從數(shù)據(jù)庫中獲取數(shù)據(jù)。
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})
  1. 創(chuàng)建模板文件:在 templates 目錄中創(chuàng)建 book_list.html 模板文件,用于渲染網(wǎng)頁。
<!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>
  1. 配置 URL 路由:在 urls.py 文件中配置 URL 路由,將請求映射到對應的視圖函數(shù)。
from django.urls import path
from .views import book_list

urlpatterns = [
    path('books/', book_list, name='book_list'),
]

這樣,當訪問 http://localhost:8000/books/ 時,就能夠顯示從數(shù)據(jù)庫中獲取的書籍列表。

0