458 lines
14 KiB
Markdown
458 lines
14 KiB
Markdown
:::warning 特别提醒
|
||
官方精心制作本教程,目的在于方便用户快速掌握软件产品的使用和部署。通过此教程,刚入行的开发者也可以快速掌握并投入产品研发。本地部署时务必请耐心阅读文档操作。
|
||
:::
|
||
|
||
## 教程概述
|
||
|
||
本教程将带你从零开始,完成一个完整的后台管理系统的搭建和运行。整个过程分为以下几个步骤:
|
||
|
||
```
|
||
1. 环境准备:安装 Python、MySQL、Redis、Node.js 等基础软件。
|
||
2. 获取源码:从官方网站下载授权源码包并解压。
|
||
3. 后端启动:安装 Python 依赖、配置环境变量、初始化数据库、启动后端服务。
|
||
4. 前端启动:安装前端依赖、启动前端开发服务器。
|
||
5. 功能验证:登录系统,验证各功能模块是否正常。
|
||
6. 新增模块:以案例管理为例,演示如何新增一个完整的业务模块。
|
||
```
|
||
|
||
## 第一步:环境准备
|
||
|
||
确保电脑上已安装以下软件:
|
||
|
||
| 软件 | 版本要求 | 用途 |
|
||
|------|----------|------|
|
||
| Python | 3.12+ | 后端运行环境 |
|
||
| MySQL | 8.0+ | 数据库 |
|
||
| Redis | 6.0+ | 缓存(验证码、JWT黑名单、限流) |
|
||
| Node.js | 18+ | 前端构建环境 |
|
||
| pnpm | 12+ | 前端包管理器 |
|
||
| Git | 最新版 | 版本控制 |
|
||
|
||
:::tip 温馨提示
|
||
详细的安装步骤请参考 [环境准备](/zh/volume1/environment) 章节。
|
||
:::
|
||
|
||
## 第二步:获取源码
|
||
|
||
前往 [官方网站](https://www.djangoadmin.cn) 购买授权后,按以下步骤获取源码:
|
||
|
||
```
|
||
1. 登录官方网站,进入「个人中心」→「我的订单」页面。
|
||
2. 在订单列表中找到已购买的授权订单,点击「下载」按钮。
|
||
3. 下载的压缩包包含完整的前后端源码、数据库脚本及部署配置文件。
|
||
4. 将压缩包解压到本地开发目录(如 E:\Projects\ 或 ~/Projects/)。
|
||
```
|
||
|
||
```bash
|
||
# 进入项目目录(以实际解压路径为准)
|
||
cd DjangoAdmin_Django_AntdVue
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
1. 源码包请务必从官方网站订单中心下载,确保获取的是正版授权的最新版本。
|
||
2. 授权有效期内可无限次下载最新版本,版本更新后可重新下载获取最新源码。
|
||
3. 解压后请先阅读根目录下的 `README.md` 了解项目基本信息。
|
||
:::
|
||
|
||
## 第三步:后端启动
|
||
|
||
### 3.1 安装 Python 依赖
|
||
|
||
```bash
|
||
# 创建虚拟环境(推荐)
|
||
python -m venv venv
|
||
|
||
# 激活虚拟环境
|
||
# Windows
|
||
venv\Scripts\activate
|
||
# Linux/macOS
|
||
source venv/bin/activate
|
||
|
||
# 安装依赖
|
||
pip install -r requirements.txt
|
||
```
|
||
|
||
:::warning 编码问题
|
||
项目的 `requirements.txt` 文件采用 UTF-16LE 编码。如果 `pip install` 报错,可以先将文件重新保存为 UTF-8 编码:
|
||
|
||
```bash
|
||
# Windows PowerShell
|
||
Get-Content requirements.txt -Encoding Unicode | Set-Content requirements_utf8.txt -Encoding UTF8
|
||
pip install -r requirements_utf8.txt
|
||
```
|
||
:::
|
||
|
||
### 3.2 配置环境变量
|
||
|
||
项目根目录下创建或编辑 `.env` 文件,配置数据库和 Redis 连接信息:
|
||
|
||
```bash
|
||
# ==================== 应用配置 ====================
|
||
DJANGO_NAME=DjangoAdmin
|
||
DJANGO_VERSION=v3.0.0
|
||
DJANGO_DEBUG=True
|
||
DJANGO_DEMO=False
|
||
|
||
# ==================== 数据库配置 ====================
|
||
DATABASE_ENGINE=django.db.backends.mysql
|
||
DATABASE_NAME=djangoadmin.django.antdvue
|
||
DATABASE_HOST=127.0.0.1
|
||
DATABASE_PORT=3306
|
||
DATABASE_USER=root
|
||
DATABASE_PASSWORD=your_password
|
||
DATABASE_PREFIX=django_
|
||
|
||
# ==================== Redis 配置 ====================
|
||
REDIS_HOST=127.0.0.1
|
||
REDIS_PORT=6379
|
||
REDIS_PASSWORD=your_redis_password
|
||
REDIS_DB=0
|
||
|
||
# ==================== 文件配置 ====================
|
||
DJANGO_FILE_URL=http://file.django.antdvue
|
||
```
|
||
|
||
:::danger 重要提示
|
||
`DATABASE_NAME` 需要提前在 MySQL 中创建对应的数据库:
|
||
```sql
|
||
CREATE DATABASE `djangoadmin.django.antdvue` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
|
||
```
|
||
:::
|
||
|
||
这些配置通过 `config/env.py` 加载,所有业务模块通过 `from config.env import ...` 引用。
|
||
|
||
### 3.3 初始化数据库
|
||
|
||
```bash
|
||
# 生成迁移文件
|
||
python manage.py makemigrations
|
||
|
||
# 执行迁移(自动建表 + 插入初始数据)
|
||
python manage.py migrate
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
迁移完成后,数据库中包含以下默认数据:
|
||
|
||
```
|
||
管理员账号:admin / 123456(超级管理员,ID=1,跳过权限校验)
|
||
默认角色:超级管理员角色
|
||
默认菜单:系统管理、内容管理等菜单及权限节点
|
||
数据字典:系统内置字典数据
|
||
系统配置:系统默认配置项
|
||
```
|
||
:::
|
||
|
||
### 3.4 启动后端服务
|
||
|
||
```bash
|
||
python manage.py runserver
|
||
```
|
||
|
||
启动成功后会看到:
|
||
|
||
```
|
||
Watching for file changes with StatReloader
|
||
Performing system checks...
|
||
|
||
System check identified no issues (0 silenced).
|
||
Django version 6.0.3, using settings 'application.settings'
|
||
Starting development server at http://127.0.0.1:8000/
|
||
Quit the server with CTRL-BREAK.
|
||
```
|
||
|
||
## 第四步:前端启动
|
||
|
||
### 4.1 安装前端依赖
|
||
|
||
```bash
|
||
# 进入前端目录
|
||
cd ui
|
||
|
||
# 安装依赖
|
||
pnpm install
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
如果安装速度较慢,可配置国内镜像源:
|
||
```bash
|
||
pnpm config set registry https://registry.npmmirror.com
|
||
```
|
||
:::
|
||
|
||
### 4.2 启动前端开发服务器
|
||
|
||
```bash
|
||
pnpm dev
|
||
```
|
||
|
||
启动成功后会看到:
|
||
|
||
```
|
||
VITE v5.x.x ready in xxx ms
|
||
|
||
➜ Local: http://localhost:8001/
|
||
```
|
||
|
||
### 4.3 访问系统
|
||
|
||
打开浏览器访问 `http://localhost:8001`,使用默认账号登录:
|
||
|
||
```
|
||
账号:admin
|
||
密码:123456
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
前端默认运行在 `8001` 端口,后端默认 `8000` 端口。`ui/.env.development` 中配置了代理,前端请求 `/api/*` 路径时自动转发到后端 `http://127.0.0.1:8000/`。
|
||
:::
|
||
|
||
## 第五步:功能验证
|
||
|
||
登录成功后,可以验证以下核心功能:
|
||
|
||
```
|
||
1. 控制台:首页仪表盘,显示系统概况。
|
||
2. 用户管理:系统管理 → 用户管理,查看用户列表、新增、编辑、删除。
|
||
3. 角色管理:系统管理 → 角色管理,管理角色和权限分配。
|
||
4. 菜单管理:系统管理 → 菜单管理,管理菜单和权限节点。
|
||
5. 数据字典:数据管理 → 字典管理,管理系统字典数据。
|
||
6. 操作日志:系统管理 → 日志管理 → 操作日志,查看操作记录。
|
||
7. 代码生成:开发工具 → 代码生成,体验代码生成功能。
|
||
```
|
||
|
||
## 第六步:新增业务模块
|
||
|
||
以「案例管理」为例,演示如何新增一个完整的 CRUD 模块。
|
||
|
||
### 6.1 后端开发
|
||
|
||
在 `application/example/` 目录下创建以下文件:
|
||
|
||
**models.py** — 定义数据模型:
|
||
|
||
```python
|
||
from django.db import models
|
||
from application.models import BaseModel
|
||
from utils.common import get_table_name
|
||
|
||
|
||
class Example(BaseModel):
|
||
"""案例模型类"""
|
||
name = models.CharField(
|
||
null=False, max_length=100, db_index=True,
|
||
verbose_name="案例名称", db_comment='案例名称'
|
||
)
|
||
avatar = models.CharField(
|
||
null=True, blank=True, max_length=255,
|
||
verbose_name="案例图片", db_comment='案例图片'
|
||
)
|
||
STATUS_CHOICES = ((1, "正常"), (2, "禁用"))
|
||
status = models.IntegerField(
|
||
null=False, choices=STATUS_CHOICES,
|
||
verbose_name="案例状态:1-正常 2-禁用", db_comment='案例状态:1-正常 2-禁用'
|
||
)
|
||
sort = models.IntegerField(
|
||
null=False, verbose_name="排序", db_comment='排序'
|
||
)
|
||
|
||
class Meta:
|
||
db_table = get_table_name('example')
|
||
db_table_comment = "案例表"
|
||
ordering = ("sort",)
|
||
```
|
||
|
||
**forms.py** — 定义表单验证:
|
||
|
||
```python
|
||
from django import forms
|
||
from application.example import models
|
||
|
||
|
||
class ExampleForm(forms.ModelForm):
|
||
"""案例表单验证类"""
|
||
name = forms.CharField(
|
||
required=True, max_length=100,
|
||
error_messages={'required': '案例名称不能为空', 'max_length': '案例名称长度不得超过100个字符'}
|
||
)
|
||
status = forms.IntegerField(
|
||
required=True, min_value=1, max_value=2,
|
||
error_messages={'required': '案例状态不能为空'}
|
||
)
|
||
sort = forms.IntegerField(
|
||
required=True,
|
||
error_messages={'required': '排序不能为空'}
|
||
)
|
||
|
||
class Meta:
|
||
model = models.Example
|
||
fields = ['name', 'avatar', 'status', 'sort']
|
||
```
|
||
|
||
**services.py** — 定义业务逻辑:
|
||
|
||
```python
|
||
import logging
|
||
from django.core.paginator import Paginator, PageNotAnInteger, InvalidPage, EmptyPage
|
||
from application.example import forms
|
||
from application.example.models import Example
|
||
from constant.constants import PAGE_SIZE
|
||
from utils import R, regular
|
||
from utils.common import parse_request_body, get_username
|
||
|
||
|
||
def get_example_page(request):
|
||
"""查询案例分页数据"""
|
||
try:
|
||
page_no = int(request.GET.get('pageNo', 1))
|
||
page_size = int(request.GET.get('pageSize', PAGE_SIZE))
|
||
query = Example.objects.filter(is_delete=False).order_by("sort")
|
||
paginator = Paginator(query, page_size)
|
||
try:
|
||
page_list = paginator.page(page_no)
|
||
except (PageNotAnInteger, InvalidPage, EmptyPage):
|
||
page_list = paginator.page(1)
|
||
page_no = 1
|
||
records = [{'id': i.id, 'name': i.name, 'status': i.status, 'sort': i.sort} for i in page_list]
|
||
return R.ok(data={'records': records, 'total': paginator.count, 'size': page_size, 'current': page_no, 'pages': paginator.num_pages})
|
||
except Exception as e:
|
||
logging.error(f"查询案例分页异常: {str(e)}")
|
||
return R.failed(msg="查询失败")
|
||
|
||
|
||
def add_example(request):
|
||
"""添加案例"""
|
||
data, error = parse_request_body(request)
|
||
if error:
|
||
return R.failed(msg=error)
|
||
form = forms.ExampleForm(data)
|
||
if not form.is_valid():
|
||
return R.failed(msg=regular.get_err(form))
|
||
try:
|
||
cleaned_data = form.cleaned_data
|
||
Example.objects.create(
|
||
name=cleaned_data.get('name'), status=cleaned_data.get('status'),
|
||
sort=cleaned_data.get('sort'), create_user=get_username(request), update_user=get_username(request)
|
||
)
|
||
return R.ok(msg="创建成功")
|
||
except Exception as e:
|
||
logging.error(f"添加案例异常: {str(e)}")
|
||
return R.failed(msg="添加失败")
|
||
```
|
||
|
||
**views.py** — 定义视图:
|
||
|
||
```python
|
||
from django.utils.decorators import method_decorator
|
||
from django.views import View
|
||
from application.example import services
|
||
from config.env import DJANGO_DEMO
|
||
from middleware.login_middleware import check_login
|
||
from middleware.permission_middleware import PermissionRequired
|
||
from utils import R
|
||
from application.operation_log.constants import LogType
|
||
from application.operation_log.decorators import operation_log
|
||
|
||
|
||
@method_decorator(check_login, name="get")
|
||
class ExamplePageView(PermissionRequired, View):
|
||
"""案例分页查询视图"""
|
||
permission_required = ("sys:example:page",)
|
||
|
||
@operation_log(title="案例管理-查询分页列表", log_type=LogType.QUERY)
|
||
def get(self, request):
|
||
return services.get_example_page(request)
|
||
|
||
|
||
@method_decorator(check_login, name="post")
|
||
class ExampleAddView(PermissionRequired, View):
|
||
"""添加案例视图"""
|
||
permission_required = ("sys:example:add",)
|
||
|
||
@operation_log(title="案例管理-添加记录", log_type=LogType.ADD)
|
||
def post(self, request):
|
||
if DJANGO_DEMO:
|
||
return R.failed("演示环境,暂无操作权限")
|
||
return services.add_example(request)
|
||
```
|
||
|
||
**urls.py** — 配置路由:
|
||
|
||
```python
|
||
from django.urls import path
|
||
from application.example import views
|
||
|
||
urlpatterns = [
|
||
path('page', views.ExamplePageView.as_view()),
|
||
path('add', views.ExampleAddView.as_view()),
|
||
]
|
||
```
|
||
|
||
### 6.2 注册路由
|
||
|
||
在 `application/urls.py` 中注册模块路由:
|
||
|
||
```python
|
||
# application/urls.py
|
||
path('example/', include('application.example.urls')),
|
||
```
|
||
|
||
在 `application/settings.py` 的 `INSTALLED_APPS` 中注册应用:
|
||
|
||
```python
|
||
INSTALLED_APPS = [
|
||
# ...
|
||
'application.example',
|
||
]
|
||
```
|
||
|
||
### 6.3 前端开发
|
||
|
||
在 `ui/src/api/tool/example.ts` 中定义接口,在 `ui/src/views/tool/example/` 中创建页面文件(index.vue、edit.vue、detail.vue、columns.ts、querySchemas.ts)。
|
||
|
||
### 6.4 配置菜单权限
|
||
|
||
在系统管理 → 菜单管理中:
|
||
|
||
```
|
||
1. 新增菜单:案例管理(路径:/tool/example,组件:tool/example/index)
|
||
2. 新增按钮:查看(sys:example:page)、新增(sys:example:add)、编辑(sys:example:update)、删除(sys:example:delete)
|
||
3. 在角色管理中为角色分配"案例管理"菜单权限
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
也可以使用代码生成器一键生成以上所有代码:`python generator.py django_example`,详见 [代码生成器](/zh/volume5/overview) 章节。
|
||
:::
|
||
|
||
## 常见问题
|
||
|
||
在部署和使用过程中,可能会遇到以下常见问题:
|
||
|
||
```
|
||
1. 端口被占用:终止占用 8000/8001 端口的进程,或修改配置。
|
||
2. 数据库连接失败:检查 .env 中的数据库配置,确认 MySQL 服务已启动。
|
||
3. Redis 连接失败:检查 Redis 服务状态和密码配置。
|
||
4. requirements.txt 编码错误:先转为 UTF-8 编码再安装。
|
||
5. pnpm install 失败:配置国内镜像 pnpm config set registry https://registry.npmmirror.com。
|
||
6. 前端白屏:检查后端服务是否启动,浏览器控制台是否有报错。
|
||
```
|
||
|
||
:::tip 温馨提示
|
||
更多问题请参考 [常见问题FAQ](/zh/volume1/faq) 章节。
|
||
:::
|
||
|
||
## 总结
|
||
|
||
通过以上步骤,你已经完成了从零搭建一个完整的后台管理系统的全过程:
|
||
|
||
```
|
||
1. 环境准备:Python 3.12 + MySQL 8.0 + Redis 6.0 + Node.js 18 + pnpm 12
|
||
2. 获取源码:从官方网站下载授权源码包
|
||
3. 后端启动:pip install → 配置 .env → 初始化数据库 → python manage.py runserver
|
||
4. 前端启动:pnpm install → pnpm dev
|
||
5. 功能验证:登录系统,验证各模块功能
|
||
6. 新增模块:models → forms → services → views → urls → 前端页面 → 菜单权限
|
||
```
|
||
|
||
整个搭建过程约 30 分钟即可完成。如果在操作过程中遇到问题,请查阅文档或在社区寻求帮助。
|