后端:Django Allauth Headless + Ninja API 前端: Tanstack Start + Query + Orval +

在这篇文章中,我想与大家分享我使用 Django Allauth 无头(Headless)后端认证,与 TanStack Start前端结合使用的经验和心得。我今年才刚刚学习 Web 编程,定有不少错漏,还望读者指正。

演示项目代码库

https://github.com/sd44/django-allauth

项目背景

Life is short, you need Python

虽然目前前后端分离架构正被 TypeScript 一体化框架(如Next.js/Tanstack Start等)冲击,特别是在要求全栈协作、类型一致性、小团队敏捷项目上,但我仍爱 Python Django 的简洁清晰、快速开发和易于维护。本文无意也无力讨论架构的优劣,就此打住吧。

Django AllauthNextAuth.js, Better Auth都提供多种认证方式(如手机号码、邮箱、通行密钥、数十种社交账户认证等)。但官方 Allauth Headless + React SPA示例仍然是 JS,而非 TS 代码;网络上也缺乏Allauth 对接 SSR(如Tanstack, Next.js) 的教程。本文便由此而生,但限于篇幅,只提出个别避坑指南。

技术栈

  • 后端:Django, Django Allauth, Django Ninja
  • 前端:ReactTanStack Start/Query
  • 数据库:Django支持的多种数据库均可,Django 也提供了近乎完美的数据库迁移指令

步骤概述

1. 设置 Django 后端

首先,安装 Django 和 Django Allauth, Django Ninja 等,参见官方文档和代码库 backend/pyproject.toml, backend/mysite/settings.py

settings.py 中需要注意如下几点。

1
[rectangle setX: 10 y: 10 width: 20 height: 20];

2. 配置 Django Allauth 路由

在 urls.py 中添加 Allauth 的 URL 路由:

from django.urls import path, include

urlpatterns = [ # … path(‘accounts/’, include(‘allauth.urls’)), # …]

3. 创建前端项目

使用 Create React App 创建前端项目:

npx create-react-app my-app

安装 TanStack Query:

npm install @tanstack/react-query

4. 使用 TanStack 进行认证

在前端中,使用 TanStack 来处理 API 请求和认证。

import { useQuery, useMutation } from ‘@tanstack/react-query’; import axios from ‘axios’;

const login = async (credentials) => { const response = await axios.post(‘/accounts/login/’, credentials); return response.data; };

const useLogin = () => { return useMutation(login); };

5. 完成认证流程

在组件中调用 useLogin,并处理登录信息。

import React, {useState} from ‘react’; import {useLogin} from ‘./api’; // 假设你的用法 import {useQueryClient} from ‘@tanstack/react-query’;

const LoginForm = () => { const queryClient = useQueryClient(); const mutation = useLogin(); const [email, setEmail] = useState(’‘); const [password, setPassword] = useState(’’);

const handleSubmit = async (event) => { event.preventDefault(); mutation.mutate({email, password}, { onSuccess: () => {// 登录成功后缓存用户数据 queryClient.invalidateQueries([‘user’]);}, onError: (error) => {console.error(“Login failed:”, error);}, }); };

return (
<input type=“email” value={email} onChange={(e) => setEmail(e.target.value)} required /> <input type=“password” value={password} onChange={(e) => setPassword(e.target.value)} required />

); };

总结

通过结合 Django Allauth 的强大功能与 TanStack 的灵活性,我成功实现了一个高效、安全的无头认证系统。这个组合不仅提升了开发效率,也使得前端开发变得更加顺畅。

Comments

2025-07-31