Logo

新人日誌

首頁關於我部落格

新人日誌

Logo

網站會不定期發佈技術筆記、職場心得相關的內容,歡迎關注本站!

網站
首頁關於我部落格
部落格
分類系列文

© 新人日誌. All rights reserved. 2020-present.

Django CRUD 的 D(Delete):資料刪除功能完整指南

最後更新:2024年11月26日Python

本文為 Django 進階教學,第 9 篇:

  1. 理解 Django 中的相對路徑與絕對路徑
  2. Django URL 路徑設置|name 參數與命名空間(Namespace)
  3. Django 串接資料庫與模型建構:完整入門指南
  4. Django 模型遷移與資料庫同步完整指南
  5. 使用 Django ORM 將資料寫入資料庫:新手入門指南
  6. Django 實現 CRUD 的 C(Create):新增資料功能完整指南
  7. Django CRUD 的 R(Read):資料讀取與顯示功能指南
  8. Django CRUD 的 U(Update):資料更新功能完整指南
  9. Django CRUD 的 D(Delete):資料刪除功能完整指南 👈 所在位置

建議閱讀本文前,先閱讀完 Django 新手教學 系列文, 若已有基本認識,可前往閱讀 高階教學 系列

在 Django 的 CRUD 操作中,D(Delete) 負責刪除資料庫中的記錄。

本指南將逐步講解如何實現刪除功能,包括路由設置、視圖邏輯、模板設計,以及如何處理刪除請求的流程。


專案目錄結構

完成刪除功能後,專案目錄的結構如下:

mysite/
├── manage.py
├── mysite/
│   ├── settings.py       # 專案配置文件
│   ├── urls.py           # 主路由配置
│
├── resumes/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py         # 定義 Resume 模型
│   ├── views.py          # 定義新增、編輯和刪除邏輯
│   ├── urls.py           # 配置應用的路由
│   ├── templates/
│       ├── resumes/
│           ├── home.html    # 顯示資料列表
│           ├── new.html     # 新增資料表單
│           ├── show.html    # 顯示單筆資料
│           ├── edit.html    # 編輯資料表單
│           ├── delete.html  # 確認刪除頁面
├── db.sqlite3            # SQLite 資料庫

配置路由

在 resumes/urls.py 中新增刪除的路由:

from django.urls import path
from . import views

app_name = 'resumes'

urlpatterns = [
    path("", views.home, name='list'),       # 主頁,顯示所有資料
    path("new/", views.new, name='nn'),     # 新增資料頁面
    path("<int:id>/", views.show, name="show"),  # 單筆資料頁面
    path("<int:id>/edit/", views.edit, name="edit"),  # 編輯資料頁面
    path("<int:id>/delete/", views.delete, name="delete"),  # 刪除資料頁面
]

編寫視圖邏輯

在 resumes/views.py 中新增 delete 函數,處理資料刪除的請求:

from django.shortcuts import render, get_object_or_404, redirect
from .models import Resume

def delete(request, id):
    # 查詢資料,若不存在返回 404
    resume = get_object_or_404(Resume, id=id)
    
    if request.method == "POST":
        # 刪除資料
        resume.delete()
        # 刪除完成後跳轉回列表頁
        return redirect("resumes:list")

    # GET 請求時顯示確認刪除頁面
    return render(
        request,
        "resumes/delete.html",
        {"resume": resume}
    )

視圖邏輯解析

  1. get_object_or_404(Resume, id=id):
    • 查詢主鍵為 id 的資料,若不存在返回 404 錯誤。
  2. 刪除資料:
    • 使用 resume.delete() 方法將該記錄從資料庫中刪除。
  3. 重定向:
    • 刪除完成後,使用 redirect("resumes:list") 導回主頁。
  4. 顯示刪除確認頁面:
    • 當請求為 GET 時,返回刪除確認頁面供用戶確認操作。

設計刪除確認頁面模板

新增 resumes/templates/resumes/delete.html,用於顯示刪除確認提示:

{% extends "shared/layout.html" %}

{% block content %}
<h1>確定是否要刪除這筆資料?</h1>

<form method="POST">
    {% csrf_token %}
    <button type="submit">確定刪除</button>
</form>
{% endblock %}

關鍵設計

  1. method="POST":
    • 使用 POST 方法提交刪除請求,符合 RESTful API 的設計原則。
  2. {% csrf_token %}:
    • 增加 CSRF 保護,防止跨站攻擊。
  3. 刪除按鈕:
    • 提交表單後將刪除請求發送到後端。

在單筆資料頁面添加刪除按鈕

修改 resumes/templates/resumes/show.html,新增刪除的超連結:

{% extends "shared/layout.html" %}

{% block content %}

<h1>{{ resume.title }}</h1>
<h3>{{ resume.skill }}</h3>

<article>
    <p>{{ resume.content }}</p>
</article>

<footer>
    <a href="{% url 'resumes:edit' resume.id %}">編輯</a>
    <a href="{% url 'resumes:delete' resume.id %}">刪除</a>
</footer>

{% endblock %}

功能測試與檢查

測試流程

  1. 訪問單筆資料頁面,例如:http://localhost:8000/resumes/1/。
  2. 點擊「刪除」按鈕,跳轉到刪除確認頁面:http://localhost:8000/resumes/1/delete/。
  3. 點擊確認刪除按鈕,檢查是否刪除成功並跳轉回主頁。

小結

通過以上步驟,我們完成了 Django CRUD 的 D(Delete)功能:

  1. 路由設置:新增刪除操作的路徑。
  2. 視圖邏輯:查詢目標資料並刪除,確保操作安全。
  3. 模板設計:
    • 添加刪除按鈕和確認頁面,為用戶提供清晰的刪除操作提示。
  4. 安全性保障:
    • 使用 CSRF 保護刪除表單,避免未經授權的刪除操作。

刪除功能的實現標誌著 Django CRUD 的完整性,為整個資料管理系統提供了關鍵的基礎功能!

目前還沒有留言,成為第一個留言的人吧!

發表留言

留言將在審核後顯示。

Python

目錄

  • 專案目錄結構
  • 配置路由
  • 編寫視圖邏輯
  • 視圖邏輯解析
  • 設計刪除確認頁面模板
  • 關鍵設計
  • 在單筆資料頁面添加刪除按鈕
  • 功能測試與檢查
  • 測試流程
  • 小結