# 以json做資料庫 因為django,sqLite的設定檔太多,所以我們其實可以用json來做資料庫。 --- # GET 實作GET API: * GET all * GET by ID > 請注意複製以下程式碼後檔名等要做修改,不是直接照抄即可run ```python= import json from django.shortcuts import render from django.conf import settings import os # 取得 JSON 路徑 JSON_PATH = os.path.join(settings.BASE_DIR, 'myapp', 'class_data.json') def index(request): with open(JSON_PATH, 'r', encoding='utf-8') as f: data = json.load(f) return render(request, 'index.html', {'names': data}) def course(request, classname_pk): with open(JSON_PATH, 'r', encoding='utf-8') as f: data = json.load(f) # 找出對應的 id course_data = next((item for item in data if item['id'] == classname_pk), None) return render(request, 'course.html', {'course': course_data}) ``` > 如果遇到編碼錯誤,可以試看看把utf-8改成utf-16 # 使用者輸入資料 實作POST > add_course.html ```htmlmixed= {% block content %} <h1>新增課程</h1> <form method="POST"> {% csrf_token %} <label for="title">課程名稱:</label> <input type="text" id="title" name="name" required> <button type="submit">送出</button> </form> {% endblock %} ``` > views.py ```python= def add_course(request): if request.method == 'POST': name = request.POST.get('name') # 讀取現有資料 with open(JSON_PATH, 'r', encoding='utf-8') as f: data = json.load(f) # 自動生成新 id new_id = max([item['pk'] for item in data]) + 1 if data else 1 # 新增資料 new_course = { 'pk': new_id, 'fields': { 'title': name } } data.append(new_course) # 寫回 JSON with open(JSON_PATH, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) return redirect('index') # 新增完成後返回首頁 # GET 請求 → 顯示表單 return render(request, 'add_course.html') ``` # 刪除資料 ```html= <a href="{% url 'delete_course' t.pk %}" style="color:#fff">退選</a> ``` ```python= def delete_course(request, pk): # 讀取現有資料 with open(JSON_PATH, 'r', encoding='utf-8') as f: data = json.load(f) # 篩出不是要刪除的那筆 data = [item for item in data if item['pk'] != pk] # 寫回 JSON with open(JSON_PATH, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) messages.success(request, '退選成功!') return redirect('index') ``` --- :::info 趁機宣傳一下我自己的個人網站跟Youtube頻道 !! **[個人網站](https://hyc.eshachem.com/) | [Youtube頻道](https://www.youtube.com/@Hy.C)** ::: @2025 Hy.C 陳毓 > Copyright ©Hy.C 陳毓 CC BY-NC-SA 4.0 | 禁止商業用途 | 轉載標記出處 | 改編作品必須在相同條款下分享。