完成wordpress到django站点的数据迁移,下一届阶段完成前端样式的轻度编写
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/media
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+21
-1
@@ -1,3 +1,23 @@
|
||||
"""
|
||||
Django 自带的管理后台配置
|
||||
在这里注册模型后,就能在 /admin/ 里管理数据
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from .models import Post
|
||||
|
||||
# Register your models here.
|
||||
|
||||
@admin.register(Post)
|
||||
class PostAdmin(admin.ModelAdmin):
|
||||
"""
|
||||
自定义 Post 在后台的显示方式
|
||||
"""
|
||||
# 列表页显示的字段
|
||||
list_display = ('title', 'status', 'published_at')
|
||||
# 右侧筛选器
|
||||
list_filter = ('status', 'published_at')
|
||||
# 顶部搜索框,搜索这些字段
|
||||
search_fields = ('title', 'content')
|
||||
# 输入标题时自动填充 slug(用标题的拼音/英文)
|
||||
prepopulated_fields = {'slug': ('title',)}
|
||||
# 列表页每页显示数量
|
||||
list_per_page = 20
|
||||
@@ -0,0 +1,57 @@
|
||||
# Generated by Django 5.2.17 on 2026-10-19 16:13
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = []
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="Post",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("title", models.CharField(max_length=200, verbose_name="标题")),
|
||||
(
|
||||
"slug",
|
||||
models.SlugField(
|
||||
max_length=200, unique=True, verbose_name="URL别名"
|
||||
),
|
||||
),
|
||||
("content", models.TextField(verbose_name="内容")),
|
||||
(
|
||||
"excerpt",
|
||||
models.TextField(blank=True, default="", verbose_name="摘要"),
|
||||
),
|
||||
("published_at", models.DateTimeField(verbose_name="发布时间")),
|
||||
("created_at", models.DateTimeField(auto_now_add=True)),
|
||||
("updated_at", models.DateTimeField(auto_now=True)),
|
||||
(
|
||||
"status",
|
||||
models.CharField(
|
||||
choices=[("draft", "草稿"), ("published", "已发布")],
|
||||
default="published",
|
||||
max_length=20,
|
||||
verbose_name="状态",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "文章",
|
||||
"verbose_name_plural": "文章",
|
||||
"db_table": "blog_post",
|
||||
"ordering": ["-published_at"],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,110 @@
|
||||
# Generated by Django 5.2.17 on 2026-10-19 16:38
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("blog", "0001_initial"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="Tag",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"name",
|
||||
models.CharField(
|
||||
max_length=100, unique=True, verbose_name="标签名称"
|
||||
),
|
||||
),
|
||||
(
|
||||
"slug",
|
||||
models.SlugField(
|
||||
max_length=100, unique=True, verbose_name="URL别名"
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "标签",
|
||||
"verbose_name_plural": "标签",
|
||||
"db_table": "blog_tag",
|
||||
"ordering": ["name"],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="Category",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"name",
|
||||
models.CharField(
|
||||
max_length=100, unique=True, verbose_name="分类名称"
|
||||
),
|
||||
),
|
||||
(
|
||||
"slug",
|
||||
models.SlugField(
|
||||
max_length=100, unique=True, verbose_name="URL别名"
|
||||
),
|
||||
),
|
||||
(
|
||||
"description",
|
||||
models.TextField(blank=True, default="", verbose_name="描述"),
|
||||
),
|
||||
(
|
||||
"parent",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="children",
|
||||
to="blog.category",
|
||||
verbose_name="父分类",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "分类",
|
||||
"verbose_name_plural": "分类",
|
||||
"db_table": "blog_category",
|
||||
"ordering": ["name"],
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="post",
|
||||
name="categories",
|
||||
field=models.ManyToManyField(
|
||||
blank=True,
|
||||
related_name="posts",
|
||||
to="blog.category",
|
||||
verbose_name="分类",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="post",
|
||||
name="tags",
|
||||
field=models.ManyToManyField(
|
||||
blank=True, related_name="posts", to="blog.tag", verbose_name="标签"
|
||||
),
|
||||
),
|
||||
]
|
||||
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
+122
-42
@@ -4,81 +4,161 @@
|
||||
Django ORM 会根据这里的类自动建表
|
||||
"""
|
||||
|
||||
"""
|
||||
博客数据模型 - 完整版
|
||||
包含文章、分类、标签
|
||||
"""
|
||||
|
||||
from django.db import models
|
||||
from django.urls import reverse
|
||||
|
||||
|
||||
class Post(models.Model):
|
||||
class Category(models.Model):
|
||||
"""
|
||||
博客文章模型
|
||||
对应数据库里的 blog_post 表
|
||||
字段设计参考 WordPress 的 wp_posts 表结构
|
||||
文章分类
|
||||
对应 WordPress 的 wp_terms + wp_term_taxonomy
|
||||
"""
|
||||
|
||||
# 文章标题,CharField 对应 VARCHAR
|
||||
# max_length=200 是数据库字段长度限制
|
||||
# verbose_name 是后台显示的名称
|
||||
title = models.CharField(max_length=200, verbose_name='标题')
|
||||
# 分类名称,比如 "技术"、"生活"
|
||||
name = models.CharField(
|
||||
max_length=100,
|
||||
unique=True,
|
||||
verbose_name='分类名称'
|
||||
)
|
||||
|
||||
# 别名(slug),用于 URL
|
||||
# 比如文章标题是 "Hello World",slug 就是 "hello-world"
|
||||
# URL 变成 /hello-world/ 而不是 /123/
|
||||
# URL 别名,比如 "tech"、"life"
|
||||
slug = models.SlugField(
|
||||
max_length=200,
|
||||
unique=True, # 不能重复
|
||||
max_length=100,
|
||||
unique=True,
|
||||
verbose_name='URL别名'
|
||||
)
|
||||
|
||||
# 文章内容,TextField 对应 TEXT 类型,无长度限制
|
||||
# WordPress 里存的是 HTML
|
||||
# 描述(WordPress 里有)
|
||||
description = models.TextField(
|
||||
blank=True,
|
||||
default='',
|
||||
verbose_name='描述'
|
||||
)
|
||||
|
||||
# 父分类(支持多级分类,大部分博客用不到,先留着)
|
||||
parent = models.ForeignKey(
|
||||
'self',
|
||||
on_delete=models.CASCADE,
|
||||
blank=True,
|
||||
null=True,
|
||||
related_name='children',
|
||||
verbose_name='父分类'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
verbose_name = '分类'
|
||||
verbose_name_plural = '分类'
|
||||
db_table = 'blog_category'
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse('blog:category_detail', kwargs={'slug': self.slug})
|
||||
|
||||
|
||||
class Tag(models.Model):
|
||||
"""
|
||||
文章标签
|
||||
对应 WordPress 的 wp_terms(taxonomy='post_tag')
|
||||
"""
|
||||
|
||||
name = models.CharField(
|
||||
max_length=100,
|
||||
unique=True,
|
||||
verbose_name='标签名称'
|
||||
)
|
||||
|
||||
slug = models.SlugField(
|
||||
max_length=100,
|
||||
unique=True,
|
||||
verbose_name='URL别名'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ['name']
|
||||
verbose_name = '标签'
|
||||
verbose_name_plural = '标签'
|
||||
db_table = 'blog_tag'
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class Post(models.Model):
|
||||
"""
|
||||
博客文章
|
||||
对应 WordPress 的 wp_posts 表
|
||||
"""
|
||||
|
||||
title = models.CharField(
|
||||
max_length=200,
|
||||
verbose_name='标题'
|
||||
)
|
||||
|
||||
slug = models.SlugField(
|
||||
max_length=200,
|
||||
unique=True,
|
||||
verbose_name='URL别名'
|
||||
)
|
||||
|
||||
# 文章内容(经典编辑器是 HTML,Markdown 插件的话可能是 md 源码)
|
||||
content = models.TextField(verbose_name='内容')
|
||||
|
||||
# 摘要,允许为空
|
||||
excerpt = models.TextField(
|
||||
blank=True, # 表单中允许为空
|
||||
default='', # 默认值
|
||||
blank=True,
|
||||
default='',
|
||||
verbose_name='摘要'
|
||||
)
|
||||
|
||||
# 发布时间,用 DateTimeField
|
||||
# 对应 WordPress 的 post_date
|
||||
published_at = models.DateTimeField(verbose_name='发布时间')
|
||||
|
||||
# 创建时间和更新时间(自动维护)
|
||||
created_at = models.DateTimeField(auto_now_add=True) # 首次创建时自动填入
|
||||
updated_at = models.DateTimeField(auto_now=True) # 每次保存时自动更新
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
# 文章状态
|
||||
STATUS_CHOICES = [
|
||||
('draft', '草稿'), # 还没写完
|
||||
('published', '已发布'), # 公开可见
|
||||
('draft', '草稿'),
|
||||
('published', '已发布'),
|
||||
]
|
||||
status = models.CharField(
|
||||
max_length=20,
|
||||
choices=STATUS_CHOICES, # 只能从列表里选
|
||||
choices=STATUS_CHOICES,
|
||||
default='published',
|
||||
verbose_name='状态'
|
||||
)
|
||||
|
||||
# ===== 新增:分类和标签的多对多关系 =====
|
||||
|
||||
# 一篇文章可以属于多个分类
|
||||
categories = models.ManyToManyField(
|
||||
Category,
|
||||
blank=True,
|
||||
related_name='posts',
|
||||
verbose_name='分类'
|
||||
)
|
||||
|
||||
# 一篇文章可以有多个标签
|
||||
tags = models.ManyToManyField(
|
||||
Tag,
|
||||
blank=True,
|
||||
related_name='posts',
|
||||
verbose_name='标签'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
"""
|
||||
Meta 类用来配置模型级别的选项
|
||||
"""
|
||||
ordering = ['-published_at'] # 默认按发布时间倒序
|
||||
verbose_name = '文章' # 后台单数名称
|
||||
verbose_name_plural = '文章' # 后台复数名称
|
||||
db_table = 'blog_post' # 指定表名(默认是 app名_类名)
|
||||
ordering = ['-published_at']
|
||||
verbose_name = '文章'
|
||||
verbose_name_plural = '文章'
|
||||
db_table = 'blog_post'
|
||||
|
||||
def __str__(self):
|
||||
"""
|
||||
返回对象的字符串表示
|
||||
在后台列表、shell 里显示时用
|
||||
"""
|
||||
return self.title
|
||||
|
||||
def get_absolute_url(self):
|
||||
"""
|
||||
返回这篇文章的详情页 URL
|
||||
reverse 会根据 urls.py 里的 name 反查出路径
|
||||
"""
|
||||
return reverse('blog:post_detail', kwargs={'slug': self.slug})
|
||||
@@ -0,0 +1,268 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}郭安的小站{% endblock %}</title>
|
||||
<style>
|
||||
/* ===== Reset ===== */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
/* ===== 基础变量 ===== */
|
||||
:root {
|
||||
--bg: #fefefe;
|
||||
--text: #1a1a1a;
|
||||
--text-light: #6b6b6b;
|
||||
--text-muted: #9b9b9b;
|
||||
--accent: #333333;
|
||||
--border: #e8e8e8;
|
||||
--code-bg: #f6f6f6;
|
||||
--radius: 4px;
|
||||
}
|
||||
|
||||
/* ===== 全局 ===== */
|
||||
body {
|
||||
font-family: "Noto Serif SC", "Source Han Serif SC", "Songti SC",
|
||||
"STSong", "Times New Roman", serif;
|
||||
font-size: 17px;
|
||||
line-height: 1.85;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* ===== 布局 ===== */
|
||||
.container {
|
||||
max-width: 680px;
|
||||
margin: 0 auto;
|
||||
padding: 0 1.5rem;
|
||||
}
|
||||
|
||||
/* ===== 头部 ===== */
|
||||
header {
|
||||
padding: 3rem 0 2rem;
|
||||
text-align: center;
|
||||
border-bottom: 1px solid var(--border);
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
header h1 a {
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
nav {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
nav a {
|
||||
color: var(--text-light);
|
||||
text-decoration: none;
|
||||
margin: 0 0.8rem;
|
||||
font-size: 0.9rem;
|
||||
font-family: -apple-system, "Noto Sans SC", sans-serif;
|
||||
}
|
||||
|
||||
nav a:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* ===== 文章列表 ===== */
|
||||
.post-item {
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
.post-item h2 {
|
||||
font-size: 1.2rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.3rem;
|
||||
}
|
||||
|
||||
.post-item h2 a {
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.post-item h2 a:hover {
|
||||
text-decoration: underline;
|
||||
text-decoration-thickness: 1px;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.post-date {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
font-family: -apple-system, "Noto Sans SC", sans-serif;
|
||||
}
|
||||
|
||||
.post-summary {
|
||||
margin-top: 0.5rem;
|
||||
color: var(--text-light);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
/* ===== 文章详情 ===== */
|
||||
article h1 {
|
||||
font-size: 1.6rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.article-meta {
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 2.5rem;
|
||||
font-family: -apple-system, "Noto Sans SC", sans-serif;
|
||||
}
|
||||
|
||||
.article-meta span {
|
||||
margin-right: 1rem;
|
||||
}
|
||||
|
||||
/* 正文排版 */
|
||||
.post-body {
|
||||
font-size: 17px;
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.post-body h2 {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
margin: 2.2em 0 0.8em;
|
||||
}
|
||||
|
||||
.post-body h3 {
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin: 1.8em 0 0.6em;
|
||||
}
|
||||
|
||||
.post-body p {
|
||||
margin-bottom: 1.3em;
|
||||
}
|
||||
|
||||
.post-body a {
|
||||
color: var(--text);
|
||||
text-decoration: underline;
|
||||
text-decoration-color: var(--text-muted);
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.post-body a:hover {
|
||||
text-decoration-color: var(--text);
|
||||
}
|
||||
|
||||
.post-body img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
margin: 1.5em 0;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.post-body blockquote {
|
||||
border-left: 3px solid var(--text-muted);
|
||||
padding: 0.5em 0 0.5em 1.2em;
|
||||
margin: 1.5em 0;
|
||||
color: var(--text-light);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.post-body ul, .post-body ol {
|
||||
margin-bottom: 1.3em;
|
||||
padding-left: 1.5em;
|
||||
}
|
||||
|
||||
.post-body li {
|
||||
margin-bottom: 0.4em;
|
||||
}
|
||||
|
||||
.post-body pre {
|
||||
background: var(--code-bg);
|
||||
padding: 1.2em;
|
||||
border-radius: var(--radius);
|
||||
overflow-x: auto;
|
||||
margin: 1.5em 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.post-body code {
|
||||
font-family: "JetBrains Mono", "Fira Code", "Consolas", monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.post-body p code, .post-body li code {
|
||||
background: var(--code-bg);
|
||||
padding: 0.15em 0.4em;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
/* ===== 分类/标签 ===== */
|
||||
.tags, .categories {
|
||||
margin-top: 3rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-light);
|
||||
font-family: -apple-system, "Noto Sans SC", sans-serif;
|
||||
}
|
||||
|
||||
.tags a, .categories a {
|
||||
color: var(--text-light);
|
||||
text-decoration: none;
|
||||
margin-right: 0.8rem;
|
||||
}
|
||||
|
||||
.tags a:hover, .categories a:hover {
|
||||
color: var(--text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* ===== 页脚 ===== */
|
||||
footer {
|
||||
margin-top: 5rem;
|
||||
padding: 2rem 0;
|
||||
text-align: center;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
border-top: 1px solid var(--border);
|
||||
font-family: -apple-system, "Noto Sans SC", sans-serif;
|
||||
}
|
||||
|
||||
/* ===== 响应式 ===== */
|
||||
@media (max-width: 768px) {
|
||||
body { font-size: 16px; }
|
||||
header { padding: 2rem 0 1.5rem; margin-bottom: 2rem; }
|
||||
.post-body { font-size: 16px; }
|
||||
article h1 { font-size: 1.35rem; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1><a href="/">郭安的小站</a></h1>
|
||||
<nav>
|
||||
<a href="/">首页</a>
|
||||
<a href="/archive/">归档</a>
|
||||
<a href="/about/">关于</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<p>© 2024 郭安的小站 · 用 Django 构建</p>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
{% extends "base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}{{ post.title }} - 郭安的小站{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<article>
|
||||
<h1>{{ post.title }}</h1>
|
||||
<div class="article-meta">
|
||||
<span>{{ post.published_at|date:"Y年m月d日 H:i" }}</span>
|
||||
{% if post.category %}
|
||||
<span><a href="/category/{{ post.category.slug }}/" style="color: var(--text-muted); text-decoration: none;">{{ post.category.name }}</a></span>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="post-body">
|
||||
{{ post.content|safe }}
|
||||
</div>
|
||||
|
||||
{% if post.tags.all %}
|
||||
<div class="tags">
|
||||
🏷
|
||||
{% for tag in post.tags.all %}
|
||||
<a href="/tag/{{ tag.slug }}/">{{ tag.name }}</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div style="margin-top: 3rem; padding-top: 1.5rem; border-top: 1px solid var(--border); font-size: 0.85rem; color: var(--text-muted); font-family: -apple-system, 'Noto Sans SC', sans-serif;">
|
||||
<a href="/" style="color: var(--text-light); text-decoration: none;">← 返回首页</a>
|
||||
</div>
|
||||
</article>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,23 @@
|
||||
{% extends "base.html" %}
|
||||
{% load static %}
|
||||
|
||||
{% block title %}郭安的小站{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% for post in posts %}
|
||||
<div class="post-item">
|
||||
<h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
|
||||
<div class="post-date">{{ post.published_at|date:"Y年m月d日" }}</div>
|
||||
{% if post.excerpt %}
|
||||
<div class="post-summary">{{ post.excerpt }}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% empty %}
|
||||
<div class="post-item" style="text-align: center; padding: 4rem 0; color: var(--text-muted);">
|
||||
<p style="margin-bottom: 0.5rem;">还没有文章</p>
|
||||
<p style="font-size: 0.9rem;">
|
||||
<a href="/admin/" style="color: var(--text-light); text-decoration: underline; text-decoration-color: var(--border); text-underline-offset: 3px;">去管理后台写一篇</a>
|
||||
</p>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
博客 app 的路由配置
|
||||
把 URL 路径映射到视图函数
|
||||
"""
|
||||
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
# app_name 用于反向解析 URL
|
||||
# 模板里用 {% url 'blog:post_list' %} 就会找到这里
|
||||
app_name = 'blog'
|
||||
|
||||
urlpatterns = [
|
||||
# 文章列表页
|
||||
# URL: /
|
||||
# name='post_list' 是反向解析的名字
|
||||
path('', views.post_list, name='post_list'),
|
||||
|
||||
# 文章详情页
|
||||
# URL: /<slug>/
|
||||
# <slug:slug> 表示这部分是 slug 类型,传给 views.post_detail 的 slug 参数
|
||||
path('<slug:slug>/', views.post_detail, name='post_detail'),
|
||||
]
|
||||
+53
-2
@@ -1,3 +1,54 @@
|
||||
from django.shortcuts import render
|
||||
"""
|
||||
视图函数
|
||||
每个函数对应一个页面
|
||||
接收 HTTP 请求,返回 HTTP 响应
|
||||
"""
|
||||
from django.shortcuts import render, get_object_or_404
|
||||
from .models import Post
|
||||
|
||||
# Create your views here.
|
||||
|
||||
def post_list(request):
|
||||
"""
|
||||
文章列表页
|
||||
|
||||
逻辑:
|
||||
1. 从数据库查询所有已发布的文章
|
||||
2. 按发布时间倒序排列(模型 Meta 里已定义 ordering)
|
||||
3. 把数据传给模板渲染
|
||||
"""
|
||||
# filter(status='published') 只取已发布的
|
||||
# 草稿不会出现在前台
|
||||
posts = Post.objects.filter(status='published')
|
||||
|
||||
# render 函数:加载模板 + 传入上下文数据 + 返回 HttpResponse
|
||||
return render(
|
||||
request, # HTTP 请求对象
|
||||
'blog/post_list.html', # 模板路径
|
||||
{'posts': posts} # 传给模板的数据(上下文)
|
||||
)
|
||||
|
||||
|
||||
def post_detail(request, slug):
|
||||
"""
|
||||
文章详情页
|
||||
|
||||
参数:
|
||||
slug: URL 里的文章别名,比如 /hello-world/ 里的 hello-world
|
||||
|
||||
逻辑:
|
||||
1. 根据 slug 查找文章
|
||||
2. 找不到就返回 404
|
||||
3. 找到就渲染详情模板
|
||||
"""
|
||||
# get_object_or_404:查到了返回对象,查不到直接抛 404
|
||||
post = get_object_or_404(
|
||||
Post, # 模型类
|
||||
slug=slug, # 查找条件:slug 匹配
|
||||
status='published' # 且状态是已发布
|
||||
)
|
||||
|
||||
return render(
|
||||
request,
|
||||
'blog/post_detail.html',
|
||||
{'post': post}
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
+39
-4
@@ -55,7 +55,7 @@ ROOT_URLCONF = "blogsite.urls"
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [],
|
||||
'DIRS': [BASE_DIR / 'blog' / 'templates'], # 模板目录
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
@@ -73,10 +73,45 @@ WSGI_APPLICATION = "blogsite.wsgi.application"
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||
|
||||
# DATABASES = {
|
||||
# "default": {
|
||||
# "ENGINE": "django.db.backends.sqlite3",
|
||||
# "NAME": BASE_DIR / "db.sqlite3",
|
||||
# }
|
||||
# }
|
||||
"""
|
||||
数据库配置
|
||||
|
||||
原来默认是 SQLite:
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
|
||||
现在换成 MySQL
|
||||
"""
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": BASE_DIR / "db.sqlite3",
|
||||
'default': {
|
||||
# 数据库引擎,指定为 MySQL
|
||||
'ENGINE': 'django.db.backends.mysql',
|
||||
# 数据库名(刚才 CREATE DATABASE 的那个名字)
|
||||
'NAME': 'blog_db',
|
||||
# MySQL 用户名
|
||||
'USER': 'root',
|
||||
# MySQL 密码
|
||||
'PASSWORD': 'guoan123', # ← 改成你自己的 MySQL 密码
|
||||
# MySQL 地址
|
||||
'HOST': '127.0.0.1', # 本地就是 127.0.0.1,远程就填 IP
|
||||
# MySQL 端口(默认 3306)
|
||||
'PORT': '3306',
|
||||
# 额外选项
|
||||
'OPTIONS': {
|
||||
# 自动提交事务
|
||||
'autocommit': True,
|
||||
# 设置连接字符集
|
||||
'charset': 'utf8mb4',
|
||||
# SQL 模式:严格模式,避免静默截断数据
|
||||
'sql_mode': 'STRICT_TRANS_TABLES',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
-2
@@ -15,9 +15,31 @@ Including another URLconf
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
|
||||
"""
|
||||
项目根路由
|
||||
所有请求先到这里,再分发到各个 app 的 urls.py
|
||||
"""
|
||||
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
from django.urls import path, include
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("admin/", admin.site.urls),
|
||||
# 管理后台
|
||||
path('admin/', admin.site.urls),
|
||||
|
||||
# 博客 app 的所有路由
|
||||
# 空字符串表示挂载到根路径
|
||||
# 比如 blog/urls.py 里定义了 '' → 实际访问 /
|
||||
path('', include('blog.urls')),
|
||||
]
|
||||
|
||||
# 开发环境下,让 Django 提供 media 文件的访问
|
||||
# 生产环境应该用 Nginx/Apache 直接提供静态文件
|
||||
if settings.DEBUG:
|
||||
urlpatterns += static(
|
||||
settings.MEDIA_URL, # URL 前缀 /media/
|
||||
document_root=settings.MEDIA_ROOT # 实际文件路径
|
||||
)
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
import django
|
||||
import re
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
django.setup()
|
||||
|
||||
from blog.models import Post
|
||||
|
||||
OLD_DOMAINS = ['an.xiaoan.xyz', 'xiaoan.xyz']
|
||||
|
||||
print("=" * 60)
|
||||
print("排查残留的图片 URL")
|
||||
print("=" * 60)
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
print(f"\n--- 搜索域名: {domain} ---\n")
|
||||
|
||||
# 正文里残留的
|
||||
posts = Post.objects.filter(content__contains=domain)
|
||||
for post in posts:
|
||||
# 用正则把所有包含该域名的 src/href/url 提取出来
|
||||
matches = re.findall(r'https?://' + re.escape(domain) + r'[^"\')\s]+', post.content)
|
||||
if matches:
|
||||
print(f" 文章: {post.title}")
|
||||
for m in set(matches): # set 去重
|
||||
print(f" {m}")
|
||||
print()
|
||||
|
||||
# 摘要里残留的
|
||||
posts = Post.objects.filter(excerpt__contains=domain)
|
||||
for post in posts:
|
||||
if not post.excerpt:
|
||||
continue
|
||||
matches = re.findall(r'https?://' + re.escape(domain) + r'[^"\')\s]+', post.excerpt)
|
||||
if matches:
|
||||
print(f" 摘要: {post.title}")
|
||||
for m in set(matches):
|
||||
print(f" {m}")
|
||||
print()
|
||||
|
||||
print("=" * 60)
|
||||
print("排查完成")
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
修复文章里的图片 URL:把旧域名替换成相对路径 /media/uploads/
|
||||
用法:python fix_image_urls.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import django
|
||||
|
||||
# 设置 Django 环境
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
django.setup()
|
||||
|
||||
from blog.models import Post
|
||||
|
||||
# ========= 配置区:如果你以后旧域名变了,改这里就行 =========
|
||||
OLD_DOMAINS = [
|
||||
'an.xiaoan.xyz',
|
||||
'xiaoan.xyz',
|
||||
]
|
||||
# =========================================================
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("开始修复图片 URL → 相对路径 /media/uploads/")
|
||||
print("=" * 60)
|
||||
|
||||
# ---- 文章正文 ----
|
||||
post_count = 0
|
||||
all_posts = Post.objects.all()
|
||||
|
||||
for post in all_posts:
|
||||
original = post.content
|
||||
changed = False
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
for scheme in ('https://', 'http://'):
|
||||
# https://域名/media/uploads/ → /media/uploads/
|
||||
post.content = post.content.replace(
|
||||
f'{scheme}{domain}/media/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
# https://域名/wp-content/uploads/ → /media/uploads/
|
||||
post.content = post.content.replace(
|
||||
f'{scheme}{domain}/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
# 兜底:纯路径形式
|
||||
post.content = post.content.replace(
|
||||
'/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
if post.content != original:
|
||||
post.save()
|
||||
post_count += 1
|
||||
print(f" [正文] {post.title}")
|
||||
changed = True
|
||||
|
||||
print(f"\n正文修复完成:{post_count} 篇")
|
||||
|
||||
# ---- 摘要 ----
|
||||
excerpt_count = 0
|
||||
for post in all_posts:
|
||||
original = post.excerpt
|
||||
if not post.excerpt:
|
||||
continue
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
for scheme in ('https://', 'http://'):
|
||||
post.excerpt = post.excerpt.replace(
|
||||
f'{scheme}{domain}/media/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
post.excerpt = post.excerpt.replace(
|
||||
f'{scheme}{domain}/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
post.excerpt = post.excerpt.replace(
|
||||
'/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
if post.excerpt != original:
|
||||
post.save()
|
||||
excerpt_count += 1
|
||||
|
||||
print(f"摘要修复完成:{excerpt_count} 篇")
|
||||
|
||||
# ---- 验证 ----
|
||||
remaining = 0
|
||||
for domain in OLD_DOMAINS:
|
||||
remaining += Post.objects.filter(content__contains=domain).count()
|
||||
remaining += Post.objects.filter(excerpt__contains=domain).count()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
if remaining == 0:
|
||||
print("✅ 全部清理干净!图片 URL 已统一为相对路径")
|
||||
else:
|
||||
print(f"⚠️ 仍有 {remaining} 处残留,请检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
"""
|
||||
WordPress → Django 数据迁移脚本
|
||||
|
||||
功能:
|
||||
1. 连接临时 WordPress 数据库(wp_temp)
|
||||
2. 读取分类、标签、文章
|
||||
3. 清洗数据(路径替换、Markdown 处理)
|
||||
4. 通过 Django ORM 写入新数据库(blog_db)
|
||||
|
||||
使用方法:
|
||||
cd blog_project
|
||||
source venv/bin/activate
|
||||
python migrate_wp.py
|
||||
|
||||
前置条件:
|
||||
- .sql 文件已导入 wp_temp 数据库
|
||||
- Django 模型已 migrate
|
||||
- 本脚本必须在 Django 项目目录下运行(需要加载 settings)
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import pymysql
|
||||
|
||||
import datetime
|
||||
from django.utils import timezone
|
||||
|
||||
from pypinyin import lazy_pinyin
|
||||
import re
|
||||
|
||||
# ========== Django 环境初始化 ==========
|
||||
# 把项目根目录加入 Python 路径
|
||||
# 这样下面才能 import django 和 blog 的模型
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 设置 Django 配置文件路径
|
||||
# 告诉 Django 用哪个 settings.py
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
|
||||
import django
|
||||
django.setup()
|
||||
|
||||
# 现在可以正常 import Django 模型了
|
||||
from blog.models import Post, Category, Tag
|
||||
from django.utils.text import slugify
|
||||
from django.db import transaction
|
||||
|
||||
|
||||
# ========== 配置区 ==========
|
||||
# WordPress 临时数据库连接信息
|
||||
WP_DB_CONFIG = {
|
||||
'host': '127.0.0.1',
|
||||
'user': 'root',
|
||||
'password': 'guoan123', # ← 改成你的 MySQL 密码
|
||||
'database': 'wp_temp',
|
||||
'charset': 'utf8mb4',
|
||||
'cursorclass': pymysql.cursors.DictCursor # 返回字典而不是元组
|
||||
}
|
||||
|
||||
# WordPress 旧域名(用于图片路径替换)
|
||||
OLD_DOMAIN = 'https://xiaoan.xyz' # ← 改成你实际的旧域名
|
||||
# 替换成新路径前缀
|
||||
NEW_MEDIA_PREFIX = '/media/uploads/'
|
||||
|
||||
|
||||
def connect_wp_db():
|
||||
"""
|
||||
连接 WordPress 临时数据库
|
||||
返回连接对象
|
||||
"""
|
||||
print("正在连接 WordPress 临时数据库...")
|
||||
conn = pymysql.connect(**WP_DB_CONFIG)
|
||||
print("✅ 连接成功")
|
||||
return conn
|
||||
|
||||
|
||||
def clean_content(html_content):
|
||||
"""
|
||||
清洗文章内容
|
||||
|
||||
做的事情:
|
||||
1. 替换图片路径(旧域名 → 新路径)
|
||||
2. (后续可扩展)Markdown 转换等
|
||||
|
||||
参数:
|
||||
html_content: 原始文章内容(HTML 或 Markdown)
|
||||
|
||||
返回:
|
||||
清洗后的内容
|
||||
"""
|
||||
if not html_content:
|
||||
return ''
|
||||
|
||||
content = html_content
|
||||
|
||||
# 1. 替换图片路径
|
||||
# WordPress 里的图片路径长这样:
|
||||
# http://旧域名/wp-content/uploads/2023/01/photo.jpg
|
||||
old_pattern = f'{OLD_DOMAIN}/wp-content/uploads/'
|
||||
content = content.replace(old_pattern, NEW_MEDIA_PREFIX)
|
||||
|
||||
# 也可能有带 https 的
|
||||
old_pattern_https = OLD_DOMAIN.replace('http://', 'https://')
|
||||
old_pattern_https += '/wp-content/uploads/'
|
||||
content = content.replace(old_pattern_https, NEW_MEDIA_PREFIX)
|
||||
|
||||
# 也可能有相对路径形式的
|
||||
content = content.replace('/wp-content/uploads/', NEW_MEDIA_PREFIX)
|
||||
|
||||
# 2. (可选)如果你用了 Markdown 编辑器插件
|
||||
# 内容可能是 Markdown 源码而不是 HTML
|
||||
# 这里先原样保留,后面可以在 C++ 或 Python 里做 md → html 转换
|
||||
# 判断依据:如果内容不以 < 开头,大概率就是 Markdown
|
||||
|
||||
return content
|
||||
|
||||
|
||||
def migrate_categories(conn):
|
||||
"""
|
||||
迁移分类
|
||||
|
||||
WordPress 里分类存在三张表里:
|
||||
- wp_terms: 存名称、slug
|
||||
- wp_term_taxonomy: 存类型(category vs post_tag)和描述
|
||||
- wp_term_relationships: 关联文章和 term
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移分类...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:所有字段都加上表名前缀,避免 ambiguous 错误
|
||||
sql = """
|
||||
SELECT
|
||||
t.term_id,
|
||||
t.name,
|
||||
t.slug,
|
||||
tt.description,
|
||||
tt.parent
|
||||
FROM wp_terms t
|
||||
INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
|
||||
WHERE tt.taxonomy = 'category'
|
||||
ORDER BY t.term_id
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 个分类")
|
||||
|
||||
category_map = {}
|
||||
|
||||
for row in rows:
|
||||
term_id = row['term_id'] # 现在 row 的 key 是 'term_id'(来自 t.term_id)
|
||||
name = row['name']
|
||||
slug = row['slug']
|
||||
description = row['description'] or ''
|
||||
parent_id = row['parent']
|
||||
|
||||
if not slug:
|
||||
slug = slugify(name)
|
||||
|
||||
category, created = Category.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={
|
||||
'name': name,
|
||||
'description': description,
|
||||
}
|
||||
)
|
||||
|
||||
if not created:
|
||||
category.name = name
|
||||
category.description = description
|
||||
category.save()
|
||||
|
||||
category_map[term_id] = category
|
||||
|
||||
status = "新建" if created else "更新"
|
||||
print(f" [{status}] 分类: {name} (slug: {slug})")
|
||||
|
||||
# 第二遍:处理父分类关系
|
||||
print("\n处理父分类关系...")
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:这里也要加表名前缀
|
||||
cursor.execute("""
|
||||
SELECT tt.term_id, tt.parent
|
||||
FROM wp_term_taxonomy tt
|
||||
INNER JOIN wp_terms t ON tt.term_id = t.term_id
|
||||
WHERE tt.taxonomy = 'category' AND tt.parent > 0
|
||||
""")
|
||||
parent_rows = cursor.fetchall()
|
||||
|
||||
for row in parent_rows:
|
||||
child_term_id = row['term_id']
|
||||
parent_term_id = row['parent']
|
||||
|
||||
if child_term_id in category_map and parent_term_id in category_map:
|
||||
child_cat = category_map[child_term_id]
|
||||
parent_cat = category_map[parent_term_id]
|
||||
child_cat.parent = parent_cat
|
||||
child_cat.save()
|
||||
|
||||
print(f"✅ 分类迁移完成,共 {len(category_map)} 个")
|
||||
return category_map
|
||||
|
||||
|
||||
def migrate_tags(conn):
|
||||
"""
|
||||
迁移标签
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移标签...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:加表名前缀
|
||||
sql = """
|
||||
SELECT
|
||||
t.term_id,
|
||||
t.name,
|
||||
t.slug
|
||||
FROM wp_terms t
|
||||
INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
|
||||
WHERE tt.taxonomy = 'post_tag'
|
||||
ORDER BY t.term_id
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 个标签")
|
||||
|
||||
tag_map = {}
|
||||
|
||||
for row in rows:
|
||||
term_id = row['term_id']
|
||||
name = row['name']
|
||||
slug = row['slug']
|
||||
|
||||
if not slug:
|
||||
slug = slugify(name)
|
||||
|
||||
tag, created = Tag.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={'name': name}
|
||||
)
|
||||
|
||||
if not created:
|
||||
tag.name = name
|
||||
tag.save()
|
||||
|
||||
tag_map[term_id] = tag
|
||||
|
||||
status = "新建" if created else "更新"
|
||||
print(f" [{status}] 标签: {name}")
|
||||
|
||||
print(f"✅ 标签迁移完成,共 {len(tag_map)} 个")
|
||||
return tag_map
|
||||
|
||||
|
||||
def migrate_posts(conn, category_map, tag_map):
|
||||
"""
|
||||
迁移文章(含分类标签关联)
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移文章...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:wp_posts 字段加表名前缀
|
||||
sql = """
|
||||
SELECT
|
||||
p.ID,
|
||||
p.post_name,
|
||||
p.post_title,
|
||||
p.post_content,
|
||||
p.post_excerpt,
|
||||
p.post_date,
|
||||
p.post_status
|
||||
FROM wp_posts p
|
||||
WHERE p.post_type = 'post'
|
||||
AND p.post_status IN ('publish', 'draft', 'private')
|
||||
ORDER BY p.post_date DESC
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 篇文章")
|
||||
|
||||
# 查询文章和分类/标签的关联
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:所有字段加表名前缀
|
||||
cursor.execute("""
|
||||
SELECT
|
||||
tr.object_id AS post_id,
|
||||
tt.term_id,
|
||||
tt.taxonomy
|
||||
FROM wp_term_relationships tr
|
||||
INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
|
||||
WHERE tt.taxonomy IN ('category', 'post_tag')
|
||||
""")
|
||||
rel_rows = cursor.fetchall()
|
||||
|
||||
# 整理关联关系
|
||||
post_relations = {}
|
||||
for rel in rel_rows:
|
||||
pid = rel['post_id']
|
||||
tid = rel['term_id']
|
||||
tax = rel['taxonomy']
|
||||
|
||||
if pid not in post_relations:
|
||||
post_relations[pid] = {'category': [], 'post_tag': []}
|
||||
if tax in ('category', 'post_tag'):
|
||||
post_relations[pid][tax].append(tid)
|
||||
|
||||
# 逐篇迁移(后面的逻辑不变)
|
||||
success_count = 0
|
||||
skip_count = 0
|
||||
|
||||
for row in rows:
|
||||
post_id = row['ID']
|
||||
title = row['post_title']
|
||||
slug = row['post_name'] or ''
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
# 如果 slug 里有 % 说明被 URL 编码了,先解码
|
||||
if '%' in slug:
|
||||
from urllib.parse import unquote
|
||||
slug = unquote(slug)
|
||||
|
||||
# 如果 slug 包含非 ASCII 字符(中文等),转拼音
|
||||
if not re.match(r'^[a-zA-Z0-9_-]+$', slug):
|
||||
# 用 pypinyin 转成拼音列表,再用 - 连接
|
||||
pinyin_list = lazy_pinyin(slug, style=0) # style=0 是普通风格
|
||||
slug = '-'.join(pinyin_list)
|
||||
# 清理掉多余的符号
|
||||
slug = re.sub(r'[^a-zA-Z0-9-]', '', slug).strip('-')
|
||||
# 如果转完是空的(极端情况),用 ID 兜底
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
content = row['post_content'] or ''
|
||||
excerpt = row['post_excerpt'] or ''
|
||||
post_date_raw = row['post_date']
|
||||
if isinstance(post_date_raw, str):
|
||||
# 如果是字符串,先解析成 datetime 对象
|
||||
post_date = datetime.datetime.strptime(post_date_raw, '%Y-%m-%d %H:%M:%S')
|
||||
# 标记为上海时区(WordPress 里存的时间通常是服务器本地时间)
|
||||
post_date = timezone.make_aware(post_date, timezone=timezone.get_fixed_timezone(480)) # UTC+8 = 480分钟
|
||||
elif isinstance(post_date_raw, datetime.datetime):
|
||||
if timezone.is_naive(post_date_raw):
|
||||
# 已经是 datetime 但不带时区,加上 UTC+8
|
||||
post_date = timezone.make_aware(post_date_raw, timezone=timezone.get_fixed_timezone(480))
|
||||
else:
|
||||
post_date = post_date_raw
|
||||
else:
|
||||
# 兜底:用当前时间
|
||||
post_date = timezone.now()
|
||||
post_status = row['post_status']
|
||||
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
status_map = {
|
||||
'publish': 'published',
|
||||
'draft': 'draft',
|
||||
'private': 'draft',
|
||||
}
|
||||
status = status_map.get(post_status, 'draft')
|
||||
|
||||
cleaned_content = clean_content(content)
|
||||
cleaned_excerpt = clean_content(excerpt)
|
||||
|
||||
try:
|
||||
with transaction.atomic():
|
||||
post, created = Post.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={
|
||||
'title': title,
|
||||
'content': cleaned_content,
|
||||
'excerpt': cleaned_excerpt,
|
||||
'published_at': post_date,
|
||||
'status': status,
|
||||
}
|
||||
)
|
||||
|
||||
if not created:
|
||||
post.title = title
|
||||
post.content = cleaned_content
|
||||
post.excerpt = cleaned_excerpt
|
||||
post.published_at = post_date
|
||||
post.status = status
|
||||
post.save()
|
||||
|
||||
if post_id in post_relations:
|
||||
rels = post_relations[post_id]
|
||||
|
||||
post.categories.clear()
|
||||
for tid in rels.get('category', []):
|
||||
if tid in category_map:
|
||||
post.categories.add(category_map[tid])
|
||||
|
||||
post.tags.clear()
|
||||
for tid in rels.get('post_tag', []):
|
||||
if tid in tag_map:
|
||||
post.tags.add(tag_map[tid])
|
||||
|
||||
success_count += 1
|
||||
action = "新建" if created else "更新"
|
||||
print(f" [{action}] 文章: {title} (slug: {slug})")
|
||||
|
||||
except Exception as e:
|
||||
skip_count += 1
|
||||
print(f" ❌ 失败: {title} - {str(e)}")
|
||||
|
||||
print(f"\n✅ 文章迁移完成: 成功 {success_count} 篇, 跳过 {skip_count} 篇")
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
主函数
|
||||
按顺序执行迁移步骤
|
||||
"""
|
||||
print("""
|
||||
╔══════════════════════════════════════╗
|
||||
║ WordPress → Django 数据迁移工具 ║
|
||||
╚══════════════════════════════════════╝
|
||||
""")
|
||||
|
||||
# 1. 连接数据库
|
||||
conn = connect_wp_db()
|
||||
|
||||
try:
|
||||
# 2. 迁移分类
|
||||
category_map = migrate_categories(conn)
|
||||
|
||||
# 3. 迁移标签
|
||||
tag_map = migrate_tags(conn)
|
||||
|
||||
# 4. 迁移文章(含分类标签关联)
|
||||
migrate_posts(conn, category_map, tag_map)
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("🎉 全部迁移完成!")
|
||||
print("=" * 50)
|
||||
print("\n接下来你可以:")
|
||||
print(" 1. 启动 runserver 查看文章列表")
|
||||
print(" 2. 确认分类和标签是否正确关联")
|
||||
print(" 3. 开始处理图片迁移(wp-content/uploads → media/uploads)")
|
||||
print(" 4. 引入 C++ 图片处理工具")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ 迁移过程中出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
finally:
|
||||
# 关闭数据库连接
|
||||
conn.close()
|
||||
print("\n数据库连接已关闭")
|
||||
|
||||
|
||||
# 脚本入口
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
import django
|
||||
import re
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
django.setup()
|
||||
|
||||
from blog.models import Post
|
||||
|
||||
# 通杀:任何包含这些域名的 URL,不管前缀后缀,一律替换成 /media/uploads/
|
||||
OLD_DOMAINS = ['an.xiaoan.xyz', 'xiaoan.xyz']
|
||||
|
||||
count = 0
|
||||
for post in Post.objects.all():
|
||||
original_content = post.content
|
||||
original_excerpt = post.excerpt or ''
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
# 匹配所有形式的 URL:http://域名/xxx、https://域名/xxx、//域名/xxx
|
||||
# 把域名+后面跟的 media/uploads 或 wp-content/uploads 替换掉
|
||||
post.content = re.sub(
|
||||
r'https?://' + re.escape(domain) + r'(/media/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.content
|
||||
)
|
||||
post.content = re.sub(
|
||||
r'https?://' + re.escape(domain) + r'(/wp-content/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.content
|
||||
)
|
||||
post.content = re.sub(
|
||||
r'//' + re.escape(domain) + r'(/media/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.content
|
||||
)
|
||||
post.content = re.sub(
|
||||
r'//' + re.escape(domain) + r'(/wp-content/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.content
|
||||
)
|
||||
|
||||
# 摘要同理
|
||||
if post.excerpt:
|
||||
post.excerpt = re.sub(
|
||||
r'https?://' + re.escape(domain) + r'(/media/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.excerpt
|
||||
)
|
||||
post.excerpt = re.sub(
|
||||
r'https?://' + re.escape(domain) + r'(/wp-content/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.excerpt
|
||||
)
|
||||
post.excerpt = re.sub(
|
||||
r'//' + re.escape(domain) + r'(/media/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.excerpt
|
||||
)
|
||||
post.excerpt = re.sub(
|
||||
r'//' + re.escape(domain) + r'(/wp-content/uploads/)',
|
||||
r'/media/uploads/',
|
||||
post.excerpt
|
||||
)
|
||||
|
||||
if post.content != original_content:
|
||||
post.save()
|
||||
count += 1
|
||||
print(f" [正文] {post.title}")
|
||||
|
||||
if post.excerpt and post.excerpt != original_excerpt:
|
||||
post.save()
|
||||
|
||||
print(f"\n✅ 通杀完成,修复 {count} 篇")
|
||||
|
||||
# 验证
|
||||
remaining = 0
|
||||
for domain in OLD_DOMAINS:
|
||||
c1 = Post.objects.filter(content__contains=domain).count()
|
||||
c2 = Post.objects.filter(excerpt__contains=domain).count()
|
||||
remaining += c1 + c2
|
||||
if c1 > 0:
|
||||
print(f" 正文仍含 {domain}: {c1} 处")
|
||||
if c2 > 0:
|
||||
print(f" 摘要仍含 {domain}: {c2} 处")
|
||||
|
||||
if remaining == 0:
|
||||
print("\n🎉 彻底干净了!")
|
||||
else:
|
||||
print(f"\n⚠️ 还有 {remaining} 处残留")
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
修复文章里的图片 URL:把旧域名替换成相对路径 /media/uploads/
|
||||
用法:python fix_image_urls.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import django
|
||||
|
||||
# 设置 Django 环境
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
django.setup()
|
||||
|
||||
from blog.models import Post
|
||||
|
||||
# ========= 配置区:如果你以后旧域名变了,改这里就行 =========
|
||||
OLD_DOMAINS = [
|
||||
'an.xiaoan.xyz',
|
||||
'xiaoan.xyz',
|
||||
]
|
||||
# =========================================================
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("开始修复图片 URL → 相对路径 /media/uploads/")
|
||||
print("=" * 60)
|
||||
|
||||
# ---- 文章正文 ----
|
||||
post_count = 0
|
||||
all_posts = Post.objects.all()
|
||||
|
||||
for post in all_posts:
|
||||
original = post.content
|
||||
changed = False
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
for scheme in ('https://', 'http://'):
|
||||
# https://域名/media/uploads/ → /media/uploads/
|
||||
post.content = post.content.replace(
|
||||
f'{scheme}{domain}/media/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
# https://域名/wp-content/uploads/ → /media/uploads/
|
||||
post.content = post.content.replace(
|
||||
f'{scheme}{domain}/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
# 兜底:纯路径形式
|
||||
post.content = post.content.replace(
|
||||
'/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
if post.content != original:
|
||||
post.save()
|
||||
post_count += 1
|
||||
print(f" [正文] {post.title}")
|
||||
changed = True
|
||||
|
||||
print(f"\n正文修复完成:{post_count} 篇")
|
||||
|
||||
# ---- 摘要 ----
|
||||
excerpt_count = 0
|
||||
for post in all_posts:
|
||||
original = post.excerpt
|
||||
if not post.excerpt:
|
||||
continue
|
||||
|
||||
for domain in OLD_DOMAINS:
|
||||
for scheme in ('https://', 'http://'):
|
||||
post.excerpt = post.excerpt.replace(
|
||||
f'{scheme}{domain}/media/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
post.excerpt = post.excerpt.replace(
|
||||
f'{scheme}{domain}/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
post.excerpt = post.excerpt.replace(
|
||||
'/wp-content/uploads/',
|
||||
'/media/uploads/'
|
||||
)
|
||||
|
||||
if post.excerpt != original:
|
||||
post.save()
|
||||
excerpt_count += 1
|
||||
|
||||
print(f"摘要修复完成:{excerpt_count} 篇")
|
||||
|
||||
# ---- 验证 ----
|
||||
remaining = 0
|
||||
for domain in OLD_DOMAINS:
|
||||
remaining += Post.objects.filter(content__contains=domain).count()
|
||||
remaining += Post.objects.filter(excerpt__contains=domain).count()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
if remaining == 0:
|
||||
print("✅ 全部清理干净!图片 URL 已统一为相对路径")
|
||||
else:
|
||||
print(f"⚠️ 仍有 {remaining} 处残留,请检查")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+26395
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user