抱歉,您的瀏覽器無法訪問本站
本頁面需要瀏覽器支持(啟用)JavaScript
了解詳情 >

在 Django 架構中,View 是負責處理使用者請求並回傳對應回應的核心元件。它連接資料(Model)與畫面(Template),決定要顯示什麼內容、如何處理邏輯,以及將資料呈現給使用者的方式。

1. 什麼是 View?

Django 中的 View 負責:

  • 接收瀏覽器傳來的 HTTP Request。
  • 處理業務邏輯(如資料查詢、表單驗證、條件分支等)。
  • 回傳適當的 HTTP Response(如 HTML、JSON、重導向等)。

View 就像一個「交通指揮員」,負責決定如何處理每一個網址請求。

2. View 的兩種寫法

2.1 函式型 View (Function-Based View, FBV)

使用最直觀的函式撰寫邏輯。

1
2
3
4
from django.http import HttpResponse

def hello_view(request):
return HttpResponse("Hello Django!")

2.2 類別型 View (Class-Based View, CBV)

使用類別封裝邏輯,適合複用與擴充。

1
2
3
4
5
6
from django.views import View
from django.http import HttpResponse

class HelloView(View):
def get(self, request):
return HttpResponse("Hello from class-based view!")

建議:簡單頁面可用 FBV,複雜頁面建議使用 CBV。

3. 設定 URL 與 View 的對應

你必須在 urls.py 中將 View 綁定對應的網址:

1
2
3
4
5
6
7
8
# urls.py
from django.urls import path
from .views import hello_view, HelloView

urlpatterns = [
path('hello/', hello_view),
path('hello-class/', HelloView.as_view()),
]
  • 函式型 View 直接使用函式名稱。
  • 類別型 View 必須使用 .as_view()。

4. 回傳 HTML 頁面 (使用 Template)

使用 render() 函式,將資料與 HTML 模版結合輸出:

1
2
3
4
5
from django.shortcuts import render

def home_view(request):
context = {'username': 'Django 使用者'}
return render(request, 'home.html', context)

對應的模版檔案 home.html:

1
<h1>歡迎,{{ username }}</h1>
  • 預設會從 templates/ 資料夾中尋找 HTML 模版,也可在 settings.py 修改 templates 對應資料夾。

5. 常見的回應類型 (Response Types)

回應類型 說明
HttpResponse 傳純文字、HTML
render() 渲染 HTML 頁面
redirect() 導向其他 URL
JsonResponse 回傳 JSON 格式(API、AJAX 用)

範例:

1
2
3
4
5
6
7
from django.http import JsonResponse, HttpResponseRedirect

def json_view(request):
return JsonResponse({'status': 'ok'})

def redirect_view(request):
return HttpResponseRedirect('/home/')

6. 類別型 View 的常用範例 (CBV)

Django 提供許多內建的泛型 View,可用於 CRUD 操作:

類型 說明
TemplateView 顯示靜態頁面
ListView 顯示多筆資料 (列表)
DetailView 顯示單筆資料(詳情)
CreateView 建立資料
UpdateView 更新資料
DeleteView 刪除資料

範例:

1
2
3
4
5
6
from django.views.generic import ListView
from .models import Article

class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'

7. 表單處理 (Form 處理基礎)

1
2
3
4
5
6
7
8
9
10
11
12
from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# 處理資料
return render(request, 'thanks.html')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})

8. View 的最佳實踐

建議做法 原因與好處
使用 CBV 處理重複模式 方便擴充、維護與重用
小型邏輯使用 FBV 更清楚直觀,適合快速開發
加入適當的註解與區分功能 提升團隊協作與可讀性
運用 LoginRequiredMixin 控制存取權限與安全性

留言