第 9 章 · URL 路由、視圖與模板

1. Django 視圖的基本概念

1.1 視圖的作用

視圖是 Django 處理 HTTP 請求的主要組件。請求進來後,Django 會依 URL 路由到對應視圖;視圖負責:

1.2 視圖的類型

  1. 函數視圖(FBV):用 Python 函數實作,簡單直觀,適合小型專案。
  2. 類視圖(CBV):用 Python 類實作,透過繼承與方法覆寫擴充,可重用性高,適合複雜邏輯。

2. 函數視圖(FBV)

2.1 基本結構

接受 request、回傳 HttpResponse 的普通函數:

# myapp/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("歡迎來到我的網站!")

2.2 處理 GET 與 POST

用 request.method 判斷請求類型:

# myapp/views.py
from django.shortcuts import render
from django.http import HttpResponse

def contact(request):
    if request.method == 'POST':
        return HttpResponse("表單已成功提交!")   # 處理表單
    else:
        return render(request, 'contact.html')     # 顯示空表單

2.3 用上下文渲染模板

用 render() 把「上下文資料 + 模板」結合成 HTML:

# myapp/views.py
from django.shortcuts import render

def index(request):
    context = {
        'title': '我的首頁',
        'welcome_message': '歡迎來到我的網站!',
    }
    return render(request, 'index.html', context)

2.4 處理表單資料

用 request.POST 取得表單欄位:

# myapp/views.py
from django.http import HttpResponse

def submit_form(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        return HttpResponse(f"姓名: {name}, 電子郵件: {email}")
    return HttpResponse("請通過 POST 提交表單")
函數視圖 FBVdef index(request): return HttpResponse(...)簡單直觀、適合小型專案以 request.method 判斷方法類視圖 CBVclass IndexView(View): def get(self, request): ...可繼承重用、結構化URL 以 .as_view() 掛載
圖:函數視圖(FBV)與類視圖(CBV)。

3. 類視圖(CBV)

3.1 基本概念

類視圖把邏輯封裝進類,每個 HTTP 方法對應一個方法(get()、post()),適合複雜、需重用的視圖。

# myapp/views.py
from django.http import HttpResponse
from django.views import View

class IndexView(View):
    def get(self, request):
        return HttpResponse("歡迎來到我的網站!")

3.2 內建通用視圖

Django 提供多個通用類視圖,常用:

# myapp/views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = 'about.html'

3.3 在 urls.py 使用類視圖

類視圖要用 .as_view() 轉成可呼叫的視圖:

from django.urls import path
from .views import IndexView, AboutView

urlpatterns = [
    path('', IndexView.as_view(), name='index'),
    path('about/', AboutView.as_view(), name='about'),
]

4. 模板(Template)系統

模板負責把視圖傳來的資料渲染成 HTML。

4.1 模板設定

在 settings.py 的 TEMPLATES 指定模板目錄;慣例放在 App 的 templates/ 下。

4.2 模板語法

<h1>{{ title }}</h1>
<p>{{ welcome_message }}</p>
{% if user.is_authenticated %}歡迎,{{ user.username }}{% endif %}

4.3 模板繼承

以基礎模板定義共用結構,子模板覆蓋其中的區塊。

base.html{% block content %}index.htmlextends base.htmlarticle.htmlextends base.htmlabout.htmlextends base.html{% block content %} 由子模板覆寫,其餘沿用 base.html
圖 模板繼承:子模板 {% extends "base.html" %},只覆寫自己需要的 block,共用導覽列與頁尾。

基礎模板

<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}我的網站{% endblock %}</title>
</head>
<body>
    <header><h1>我的網站標題</h1></header>
    <nav>
        <ul>
            <li><a href="/">首頁</a></li>
            <li><a href="/about/">關於我們</a></li>
        </ul>
    </nav>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer><p>&copy; 2024 我的網站</p></footer>
</body>
</html>

子模板

<!-- templates/index.html -->
{% extends 'base.html' %}
{% block title %}首頁 - 我的網站{% endblock %}
{% block content %}
    <h2>歡迎來到我的網站!</h2>
    <p>這是首頁的具體內容。</p>
{% endblock %}

4.4 模板過濾器

過濾器(用 |)用來修改變數輸出:

<p>當前日期:{{ current_date|date:"Y-m-d" }}</p>
<p>文章數量:{{ num_posts|default:"暫無文章" }}</p>

4.5 自定義過濾器與標籤

放在 App 的 templatetags/ 下,先 register = template.Library()。

自定義過濾器

# myapp/templatetags/my_filters.py
from django import template
register = template.Library()

@register.filter(name='add_exclamation')
def add_exclamation(value):
    return f"{value}!"
<!-- templates/index.html -->
{{ welcome_message|add_exclamation }}

自定義標籤

# myapp/templatetags/my_tags.py
from django import template
register = template.Library()

@register.simple_tag
def multiply(a, b):
    return a * b
<!-- templates/calculate.html -->
{% load my_tags %}
<p>結果:{% multiply 5 3 %}</p>

5. 本章總結

本章介紹了 Django 的視圖(函數視圖、類視圖)與模板系統(語法、上下文渲染、模板繼承、過濾器與自定義標籤),是打造動態頁面的核心。