新手指南|使用 Django 實現後端會員登入、註冊功能
更新日期: 2025 年 1 月 29 日
本文為 Django 登入註冊功能(後端)系列文,第 1 篇
- 新手指南|使用 Django 實現後端會員登入、註冊功能 👈所在位置
- Django Rest Framework (DRF) 新手指南:為什麼選擇 DRF 建構 API?
- Django Rest Framework (DRF) 新手指南:用 ViewSets 快速構建 CRUD API
- 初學者指南:理解 Token 認證及其運作方式
- Django REST Framework (DRF) 認證方式、預設權限規則|新手指南
- Django Rest Framework 入門指南:如何正確處理 HTTP 狀態碼
- 初學者指南:深入了解 Django 的 create_user 方法
- 新手指南:深入了解 Django 的 authenticate 方法
- Django REST Framework|@permission_classes指導手冊
- 使用 Postman 測試 Django 後端的註冊、登入與登出功能
在現代 Web 開發中,「前後端分離」是一種常見架構。
後端的主要職責是提供 API,讓前端進行資料請求並渲染頁面。
這篇文章將帶您從零開始,使用 Django 和 Django Rest Framework (DRF) 構建一個基本的會員登入與註冊系統。
無論您是剛接觸 Django 還是 API 開發的新手,都可以輕鬆跟隨以下步驟完成後端功能。
設置 Django Rest Framework (DRF)
在開始撰寫 API 之前,必須安裝並設定 Django Rest Framework。
安裝必要套件
執行以下指令安裝 DRF:
pip install djangorestframework
接著,將其加入 Django 專案的 INSTALLED_APPS
:
# settings.py
INSTALLED_APPS = [
...,
'rest_framework', # REST framework
'rest_framework.authtoken', # Token-based authentication (可選)
'django.contrib.auth', # 認證相關
]
設定 REST Framework 的全域配置
在 settings.py
中,設定 REST Framework 的預設認證方式,例如 Token 認證:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
提示:如果需要更安全的認證方式,可以改用 JWT 認證(推薦套件:SimpleJWT)。
建立 Django API
接下來,我們會實現會員註冊、登入及登出 API。
註冊功能
在 accounts/views.py
中撰寫註冊 API:
from django.contrib.auth.models import User
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
data = request.data
username = data.get('username')
email = data.get('email')
password = data.get('password')
password2 = data.get('password2')
if password != password2:
return Response({'error': '密碼不一致!'}, status=status.HTTP_400_BAD_REQUEST)
if User.objects.filter(username=username).exists():
return Response({'error': '使用者名稱已被註冊!'}, status=status.HTTP_400_BAD_REQUEST)
if User.objects.filter(email=email).exists():
return Response({'error': 'Email 已被註冊!'}, status=status.HTTP_400_BAD_REQUEST)
User.objects.create_user(username=username, email=email, password=password)
return Response({'message': '使用者註冊成功!'}, status=status.HTTP_201_CREATED)
登入功能
撰寫登入 API,生成並返回 Token:
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
data = request.data
username = data.get('username')
password = data.get('password')
user = authenticate(username=username, password=password)
if user is None:
return Response({'error': '登入失敗!'}, status=status.HTTP_401_UNAUTHORIZED)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key, 'message': '登入成功!'}, status=status.HTTP_200_OK)
登出功能
實現登出 API,刪除用戶的 Token:
@api_view(['POST'])
def logout(request):
request.user.auth_token.delete()
return Response({'message': '登出成功!'}, status=status.HTTP_200_OK)
設置 API 路由
在應用中定義路由
在 accounts/urls.py
中定義 API 路徑:
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.register, name='api-register'),
path('login/', views.login, name='api-login'),
path('logout/', views.logout, name='api-logout'),
]
將應用路由加入主專案
在專案的 urls.py
文件中加入 accounts
應用的路由:
from django.urls import path, include
urlpatterns = [
path('api/accounts/', include('accounts.urls')), # 包含 accounts 應用的 API 路由
]
測試 API
可以使用工具如 Postman 或 Curl 測試 API。
測試註冊
POST /api/accounts/register/
Content-Type: application/json
{
"username": "testuser",
"email": "[email protected]",
"password": "password123",
"password2": "password123"
}
測試登入
POST /api/accounts/login/
Content-Type: application/json
{
"username": "testuser",
"password": "password123"
}
測試登出
POST /api/accounts/logout/
Authorization: Token <your_token>
前端處理
前端可以使用 Axios 或 Fetch API 與 Django 的 API 互動。
以下是使用 Axios 的範例:
使用 Axios 進行登入請求(React 範例)
import axios from 'axios';
const login = async (username, password) => {
try {
const response = await axios.post('http://127.0.0.1:8000/api/accounts/login/', {
username,
password,
});
console.log(response.data); // 包含 Token
localStorage.setItem('token', response.data.token); // 儲存 Token
} catch (error) {
console.error(error.response.data);
}
};
進階功能建議
若需要更強大的功能,可以考慮以下擴展:
- JWT 認證
替換 Token 認證為 JSON Web Token (JWT),可使用 SimpleJWT 套件。 - 密碼重設功能
利用 Django 提供的PasswordResetView
和PasswordResetConfirmView
實現密碼重設。 - 用戶資料更新 API
建立/api/accounts/profile/
讓用戶更新個人資料,如名稱或大頭貼。
結語
以上步驟展示了如何使用 Django 實現會員註冊、登入及登出功能,並與前端進行互動。
透過這些 API,您可以快速搭建出適合前後端分離的認證系統。如果您有任何問題或需要更進階的功能,歡迎與我討論!