Compare commits

..
10 Commits
25 changed files with 1613 additions and 15 deletions
+183 -1
View File
@@ -1,10 +1,25 @@
from pathlib import Path
from django.contrib import admin
from .models import SiteSettings, Banner
from django.db import models
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.urls import path, reverse
from django.utils.html import format_html
from django.contrib import messages
from django.views.decorators.http import require_POST
from django.core.exceptions import PermissionDenied
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from .models import SiteSettings, Banner, DeployLog, MediaFile
from .deploy import start_deploy
from . import file_manager as fm
@admin.register(SiteSettings)
class SiteSettingsAdmin(admin.ModelAdmin):
list_display = ('id',)
formfield_overrides = {
models.TextField: {'widget': CKEditorUploadingWidget},
}
fieldsets = (
('基础信息', {
'fields': ('site_name_zh', 'site_name_en', 'site_logo',
@@ -15,6 +30,9 @@ class SiteSettingsAdmin(admin.ModelAdmin):
'company_address_zh', 'company_address_en',
'company_phone', 'company_email')
}),
('关于我们', {
'fields': ('about_content_zh', 'about_content_en'),
}),
('社交媒体', {
'fields': ('wechat_qr', 'weibo_url'),
'classes': ('collapse',)
@@ -56,3 +74,167 @@ class BannerAdmin(admin.ModelAdmin):
'fields': ('link_url', 'sort_order', 'is_active')
}),
)
@admin.register(DeployLog)
class DeployLogAdmin(admin.ModelAdmin):
list_display = ('started_at', 'status', 'triggered_by', 'duration', 'view_output_link')
list_filter = ('status',)
readonly_fields = ('id', 'triggered_by', 'started_at', 'finished_at', 'status', 'output')
ordering = ('-started_at',)
list_per_page = 20
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return request.user.is_superuser
def view_output_link(self, obj):
if not obj.id:
return '-'
url = reverse('admin:core_deploylog_detail', args=[obj.id])
return format_html('<a href="{}" target="_blank">查看日志</a>', url)
view_output_link.short_description = '输出日志'
def get_urls(self):
urls = super().get_urls()
custom_urls = [
path(
'deploy/',
self.admin_site.admin_view(self.deploy_view),
name='core_deploy_trigger',
),
path(
'<path:log_id>/detail/',
self.admin_site.admin_view(self.detail_view),
name='core_deploylog_detail',
),
]
return custom_urls + urls
def deploy_view(self, request):
"""触发一次部署。"""
# 防止并发部署:检查是否有正在执行的任务
if DeployLog.objects.filter(status='running').exists():
messages.error(request, '已有部署任务正在执行,请等待其完成后再试。')
return redirect('admin:core_deploylog_changelist')
log = start_deploy(user=request.user)
messages.success(request, f'部署已启动(日志 ID: {str(log.id)[:8]}),请刷新页面查看进度。')
return redirect('admin:core_deploylog_detail', log_id=str(log.id))
def detail_view(self, request, log_id):
"""展示单条部署日志的实时输出。"""
try:
log = DeployLog.objects.get(id=log_id)
except (DeployLog.DoesNotExist, ValueError):
messages.error(request, '部署日志不存在。')
return redirect('admin:core_deploylog_changelist')
context = {
**self.admin_site.each_context(request),
'opts': self.model._meta,
'log': log,
'title': f'部署日志 - {log.started_at:%Y-%m-%d %H:%M:%S}',
'is_running': log.status == 'running',
}
return render(request, 'admin/core/deploylog/detail.html', context)
def changelist_view(self, request, extra_context=None):
"""在列表页顶部插入"一键部署"按钮。"""
extra_context = extra_context or {}
extra_context['deploy_url'] = reverse('admin:core_deploy_trigger')
extra_context['has_running'] = DeployLog.objects.filter(status='running').exists()
return super().changelist_view(request, extra_context)
# ---------------------------------------------------------------
# 媒体文件管理:通过一个 managed=False 的虚拟模型挂到左侧侧栏
# ---------------------------------------------------------------
@admin.register(MediaFile)
class MediaFileAdmin(admin.ModelAdmin):
"""媒体文件管理 Admin:覆写 changelist_view 渲染自定义文件管理器页面。
该模型 managed=False,不访问数据库,默认权限被禁用。
自定义的 delete/preview URL 通过 get_urls() 注册在 admin/core/mediafile/ 下。
"""
def has_module_permission(self, request):
return request.user.is_superuser or request.user.has_perm('core.manage_files')
def has_view_permission(self, request, obj=None):
return self.has_module_permission(request)
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
def get_urls(self):
# 自定义 URL 必须放在前面,避免被默认的 changelist URL 拦截
urls = [
path('delete/', self.admin_site.admin_view(require_POST(self.delete_view)),
name='core_mediafile_delete'),
path('preview/', self.admin_site.admin_view(self.preview_view),
name='core_mediafile_preview'),
]
return urls + super().get_urls()
def changelist_view(self, request, extra_context=None):
"""覆写 changelist:直接渲染媒体文件管理页面。"""
if not (request.user.is_superuser or request.user.has_perm('core.manage_files')):
raise PermissionDenied
sub_path = request.GET.get('path', '').strip()
data = fm.list_media_files(sub_path)
usage = fm.get_storage_usage()
context = {
**admin.site.each_context(request),
'title': '媒体文件管理',
'data': data,
'usage': usage,
# changelist URL 就是当前 admin/core/mediafile/
'list_url': reverse('admin:core_mediafile_changelist'),
'delete_url': reverse('admin:core_mediafile_delete'),
'preview_url': reverse('admin:core_mediafile_preview'),
'opts': self.model._meta,
}
return render(request, 'admin/core/mediafile/change_list.html', context)
def delete_view(self, request):
"""删除文件的 AJAX/POST 接口。"""
if not (request.user.is_superuser or request.user.has_perm('core.manage_files')):
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({'ok': False, 'msg': '无权删除'}, status=403)
raise PermissionDenied
rel_path = request.POST.get('path', '').strip()
ok, msg = fm.delete_media_file(rel_path)
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({'ok': ok, 'msg': msg})
if ok:
messages.success(request, msg)
else:
messages.error(request, msg)
# 回到原目录
parent = str(Path(rel_path).parent) if rel_path else ''
if parent == '.':
parent = ''
return redirect(f"{reverse('admin:core_mediafile_changelist')}?path={parent}")
def preview_view(self, request):
"""预览文件信息的 JSON 接口。"""
rel_path = request.GET.get('path', '').strip()
data = fm.list_media_files(rel_path and str(Path(rel_path).parent) or '')
target = next((f for f in data['files'] if f['path'] == rel_path), None)
if not target:
return JsonResponse({'ok': False, 'msg': '文件不存在'}, status=404)
return JsonResponse({'ok': True, 'file': target})
+5
View File
@@ -5,3 +5,8 @@ class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.core'
verbose_name = '内容管理'
def ready(self):
# 注册所有 ImageField 文件的自动清理信号
from .signals import _register_cleanup_signals # noqa: F401
_register_cleanup_signals()
+177
View File
@@ -0,0 +1,177 @@
"""在线部署模块:从 Git 拉取最新代码并完成更新。
执行流程:
1. git pull origin <branch>
2. pip install -r requirements.txt
3. python manage.py migrate
4. python manage.py collectstatic --noinput
5. sudo supervisorctl restart tgoim(可选,需配置 sudoers)
为避免 supervisor 重启时中断当前请求,部署在后台线程中执行,
用户可在后台管理界面查看实时日志。
"""
import os
import sys
import subprocess
import threading
from pathlib import Path
from django.conf import settings
from django.utils import timezone
BASE_DIR = settings.BASE_DIR
# 单步命令超时(秒)
STEP_TIMEOUT = 180
# 拉取的远程分支,可通过 settings.GIT_DEPLOY_BRANCH 覆盖
GIT_BRANCH = getattr(settings, 'GIT_DEPLOY_BRANCH', 'main')
# Supervisor 服务名,可通过 settings.SUPERVISOR_SERVICE_NAME 覆盖
SUPERVISOR_SERVICE = getattr(settings, 'SUPERVISOR_SERVICE_NAME', 'tgoim')
def _venv_python():
"""返回虚拟环境中的 python 可执行文件路径。"""
if os.name == 'nt':
candidate = BASE_DIR / 'venv' / 'Scripts' / 'python.exe'
else:
candidate = BASE_DIR / 'venv' / 'bin' / 'python'
if candidate.exists():
return str(candidate)
return sys.executable
def _venv_pip():
"""返回虚拟环境中的 pip 可执行文件路径。"""
if os.name == 'nt':
candidate = BASE_DIR / 'venv' / 'Scripts' / 'pip.exe'
else:
candidate = BASE_DIR / 'venv' / 'bin' / 'pip'
if candidate.exists():
return str(candidate)
return [sys.executable, '-m', 'pip']
def _run_step(log_lines, cmd, timeout=STEP_TIMEOUT, env=None):
"""执行一条命令,将输出追加到 log_lines,返回是否成功。"""
if isinstance(cmd, str):
display = cmd
args = cmd.split()
else:
display = ' '.join(str(c) for c in cmd)
args = [str(c) for c in cmd]
# 为 git 命令自动加上 safe.directory 配置,避免 "dubious ownership" 报错
# (Django 通常以 www-data 运行,但项目目录所有者可能是 root)
if args and args[0] == 'git':
args = ['git', '-c', f'safe.directory={BASE_DIR}'] + args[1:]
display = ' '.join(args)
log_lines.append(f'\n$ {display}')
try:
run_env = None
if env:
run_env = {**os.environ, **env}
result = subprocess.run(
args, cwd=str(BASE_DIR),
capture_output=True, text=True, timeout=timeout,
env=run_env,
)
if result.stdout:
log_lines.append(result.stdout.rstrip())
if result.stderr:
log_lines.append(result.stderr.rstrip())
if result.returncode != 0:
log_lines.append(f'命令失败,退出码: {result.returncode}')
return False
return True
except subprocess.TimeoutExpired:
log_lines.append(f'命令超时({timeout}s)')
return False
except FileNotFoundError as e:
log_lines.append(f'命令未找到: {e}')
return False
except Exception as e:
log_lines.append(f'执行异常: {e}')
return False
def _run_deploy(log_id):
"""后台线程执行部署流程。"""
from .models import DeployLog
log = DeployLog.objects.get(id=log_id)
log_lines = []
venv_python = _venv_python()
venv_pip = _venv_pip()
pip_cmd = venv_pip if isinstance(venv_pip, list) else [venv_pip]
try:
log_lines.append(f'开始部署,分支: {GIT_BRANCH}')
log_lines.append(f'工作目录: {BASE_DIR}')
log_lines.append(f'Python: {venv_python}')
log.output = '\n'.join(log_lines)
log.save()
# 1. 拉取代码
log_lines.append('\n========== [1/5] 拉取最新代码 ==========')
log.output = '\n'.join(log_lines)
log.save()
if not _run_step(log_lines, ['git', 'pull', 'origin', GIT_BRANCH]):
raise RuntimeError('git pull 失败')
# 2. 安装依赖
log_lines.append('\n========== [2/5] 安装 Python 依赖 ==========')
log.output = '\n'.join(log_lines)
log.save()
if not _run_step(log_lines, pip_cmd + ['install', '-r', 'requirements.txt']):
raise RuntimeError('pip install 失败')
# 3. 数据库迁移
log_lines.append('\n========== [3/5] 执行数据库迁移 ==========')
log.output = '\n'.join(log_lines)
log.save()
if not _run_step(log_lines, [venv_python, 'manage.py', 'migrate']):
raise RuntimeError('migrate 失败')
# 4. 收集静态文件
log_lines.append('\n========== [4/5] 收集静态文件 ==========')
log.output = '\n'.join(log_lines)
log.save()
if not _run_step(log_lines, [venv_python, 'manage.py', 'collectstatic', '--noinput']):
raise RuntimeError('collectstatic 失败')
# 5. 重启服务
log_lines.append('\n========== [5/5] 重启应用服务 ==========')
# 先把成功状态写入数据库,因为 supervisorctl restart 可能会终止当前进程
log.status = 'success'
log_lines.append(f'代码更新成功,正在重启服务 {SUPERVISOR_SERVICE} ...')
log.output = '\n'.join(log_lines)
log.finished_at = timezone.now()
log.save()
restart_ok = _run_step(log_lines, ['sudo', '-n', 'supervisorctl', 'restart', SUPERVISOR_SERVICE])
if not restart_ok:
log_lines.append(
f'提示: 自动重启失败。请在服务器手动执行: '
f'sudo supervisorctl restart {SUPERVISOR_SERVICE}'
)
# 状态仍记为 success,因为代码已更新成功,仅重启未生效
log_lines.append('\n部署流程结束。')
log.output = '\n'.join(log_lines)
log.save()
except Exception as e:
log.status = 'failed'
log_lines.append(f'\n部署失败: {e}')
log.output = '\n'.join(log_lines)
log.finished_at = timezone.now()
log.save()
def start_deploy(user=None):
"""启动一次部署(后台线程执行),返回 DeployLog 对象。"""
from .models import DeployLog
log = DeployLog.objects.create(triggered_by=user, status='running')
thread = threading.Thread(target=_run_deploy, args=(str(log.id),), daemon=True)
thread.start()
return log
+159
View File
@@ -0,0 +1,159 @@
"""媒体文件管理:浏览和删除上传到 MEDIA_ROOT 的文件。
包含:
- list_media_files():按目录结构列出所有文件/子目录
- delete_media_file(rel_path):删除指定相对路径的文件
- get_storage_usage():统计目录占用大小
"""
import os
from pathlib import Path
from django.conf import settings
MEDIA_ROOT = settings.MEDIA_ROOT
def _rel(path: Path) -> str:
"""把绝对路径转换为相对于 MEDIA_ROOT 的 Unix 风格路径。"""
return path.relative_to(MEDIA_ROOT).as_posix()
def _human_size(num_bytes: int) -> str:
"""把字节数格式化成人类可读字符串。"""
for unit in ('B', 'KB', 'MB', 'GB'):
if num_bytes < 1024:
return f'{num_bytes:.1f} {unit}' if unit != 'B' else f'{int(num_bytes)} {unit}'
num_bytes /= 1024
return f'{num_bytes:.1f} TB'
def list_media_files(sub_path: str = ''):
"""列出 MEDIA_ROOT/sub_path 下的文件和子目录。
返回结构:
{
'current_path': 'uploads/',
'parent_path': None or 'uploads/',
'subdirs': [{'name': '2026', 'path': 'uploads/2026', 'count': 12, 'size': '1.2 MB'}],
'files': [{'name': 'a.jpg', 'path': 'uploads/a.jpg', 'size': '200 KB',
'url': '/media/uploads/a.jpg', 'modified': datetime}]
}
"""
root = MEDIA_ROOT / Path(sub_path) if sub_path else MEDIA_ROOT
# 防止路径穿越
try:
root.resolve().relative_to(MEDIA_ROOT.resolve())
except ValueError:
root = MEDIA_ROOT
if not root.exists():
root.mkdir(parents=True, exist_ok=True)
current_rel = _rel(root) if root != MEDIA_ROOT else ''
parent_rel = str(Path(current_rel).parent) if current_rel else None
if parent_rel == '.':
parent_rel = ''
subdirs = []
files = []
try:
entries = sorted(root.iterdir(), key=lambda p: (p.is_file(), p.name.lower()))
except PermissionError:
entries = []
for entry in entries:
try:
if entry.is_dir():
file_count = sum(1 for f in entry.rglob('*') if f.is_file())
total_bytes = sum(f.stat().st_size for f in entry.rglob('*') if f.is_file())
subdirs.append({
'name': entry.name,
'path': _rel(entry),
'file_count': file_count,
'size': _human_size(total_bytes),
})
elif entry.is_file():
stat = entry.stat()
rel = _rel(entry)
files.append({
'name': entry.name,
'path': rel,
'size': _human_size(stat.st_size),
'size_bytes': stat.st_size,
'url': f'{settings.MEDIA_URL}{rel}',
'modified': stat.st_mtime,
'is_image': entry.suffix.lower() in {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'},
})
except (PermissionError, OSError):
continue
# 构建面包屑:每一级的 name 和完整路径
breadcrumb = []
if current_rel:
parts = Path(current_rel).parts
built = []
for p in parts:
built.append(p)
breadcrumb.append({'name': p, 'path': '/'.join(built)})
return {
'current_path': current_rel,
'parent_path': parent_rel,
'breadcrumb': breadcrumb,
'subdirs': subdirs,
'files': files,
'total_size': _human_size(sum(f['size_bytes'] for f in files)),
}
def delete_media_file(rel_path: str) -> tuple[bool, str]:
"""删除指定相对路径的文件。仅允许删除 MEDIA_ROOT 内的文件。
返回 (是否成功, 提示信息)。
"""
if not rel_path:
return False, '路径不能为空'
target = (MEDIA_ROOT / Path(rel_path)).resolve()
try:
target.relative_to(MEDIA_ROOT.resolve())
except ValueError:
return False, '非法路径:只能删除 media 目录内的文件'
if not target.exists():
return False, '文件不存在'
if not target.is_file():
return False, '目标不是文件'
try:
target.unlink()
except PermissionError:
return False, '没有删除权限,请联系服务器管理员检查 www-data 对 media 目录的权限'
except OSError as e:
return False, f'删除失败:{e}'
return True, f'已删除:{rel_path}'
def get_storage_usage() -> dict:
"""返回 media 根目录各子目录的占用概览。"""
summary = []
total_bytes = 0
if not MEDIA_ROOT.exists():
return {'top_dirs': [], 'total': '0 B'}
for entry in sorted(MEDIA_ROOT.iterdir(), key=lambda p: p.name.lower()):
if entry.is_dir():
size = sum(f.stat().st_size for f in entry.rglob('*') if f.is_file())
count = sum(1 for f in entry.rglob('*') if f.is_file())
total_bytes += size
summary.append({
'name': entry.name + '/',
'size': _human_size(size),
'count': count,
})
elif entry.is_file():
size = entry.stat().st_size
total_bytes += size
return {
'top_dirs': summary,
'total': _human_size(total_bytes),
}
@@ -0,0 +1,23 @@
# Generated by Django 5.0.14 on 2026-08-05 00:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='sitesettings',
name='about_content_en',
field=models.TextField(blank=True, default='', verbose_name='关于我们内容(英文)'),
),
migrations.AddField(
model_name='sitesettings',
name='about_content_zh',
field=models.TextField(blank=True, default='', verbose_name='关于我们内容(中文)'),
),
]
+32
View File
@@ -0,0 +1,32 @@
# Generated manually for DeployLog model
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('core', '0002_sitesettings_about_content_en_and_more'),
]
operations = [
migrations.CreateModel(
name='DeployLog',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('started_at', models.DateTimeField(auto_now_add=True, verbose_name='开始时间')),
('finished_at', models.DateTimeField(blank=True, null=True, verbose_name='结束时间')),
('status', models.CharField(choices=[('running', '执行中'), ('success', '成功'), ('failed', '失败')], default='running', max_length=20, verbose_name='状态')),
('output', models.TextField(blank=True, default='', verbose_name='输出日志')),
('triggered_by', models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='deploy_logs', to=settings.AUTH_USER_MODEL, verbose_name='触发者')),
],
options={
'verbose_name': '部署日志',
'verbose_name_plural': '部署日志',
'ordering': ['-started_at'],
},
),
]
+26
View File
@@ -0,0 +1,26 @@
# Generated manually for MediaFile proxy model
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_deploylog'),
]
operations = [
migrations.CreateModel(
name='MediaFile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'verbose_name': '媒体文件',
'verbose_name_plural': '媒体文件管理',
'managed': False,
'default_permissions': [],
'permissions': [('manage_files', '可管理媒体文件')],
},
),
]
+57
View File
@@ -1,4 +1,25 @@
import uuid
from django.db import models
from django.utils.translation import gettext_lazy as _
class MediaFile(models.Model):
"""代理模型:仅用于在后台侧栏显示"媒体文件管理"入口。
真实文件系统管理逻辑在 core/file_manager.py 中。
此模型不会迁移数据库(managed = False)。
"""
class Meta:
managed = False
verbose_name = '媒体文件'
verbose_name_plural = '媒体文件管理'
default_permissions = [] # 禁用默认的 add/change/delete/view
permissions = [
('manage_files', '可管理媒体文件'),
]
# 任意加一个字段,因为 Meta.managed=False,不会真的建表
id = models.BigAutoField(primary_key=True)
class SiteSettings(models.Model):
@@ -28,6 +49,9 @@ class SiteSettings(models.Model):
seo_description_zh = models.CharField('默认SEO描述(中文)', max_length=300, blank=True, default='')
seo_description_en = models.CharField('默认SEO描述(英文)', max_length=300, blank=True, default='')
about_content_zh = models.TextField('关于我们内容(中文)', blank=True, default='')
about_content_en = models.TextField('关于我们内容(英文)', blank=True, default='')
class Meta:
verbose_name = '网站设置'
verbose_name_plural = verbose_name
@@ -60,3 +84,36 @@ class Banner(models.Model):
def __str__(self):
return self.title_zh or f'Banner #{self.id}'
class DeployLog(models.Model):
STATUS_CHOICES = [
('running', '执行中'),
('success', '成功'),
('failed', '失败'),
]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
triggered_by = models.ForeignKey(
'auth.User', on_delete=models.SET_NULL, null=True,
verbose_name='触发者', related_name='deploy_logs'
)
started_at = models.DateTimeField('开始时间', auto_now_add=True)
finished_at = models.DateTimeField('结束时间', null=True, blank=True)
status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='running')
output = models.TextField('输出日志', blank=True, default='')
class Meta:
ordering = ['-started_at']
verbose_name = '部署日志'
verbose_name_plural = verbose_name
def __str__(self):
return f'{self.started_at:%Y-%m-%d %H:%M:%S} - {self.get_status_display()}'
@property
def duration(self):
if self.finished_at:
delta = self.finished_at - self.started_at
return f'{delta.total_seconds():.1f}s'
return '-'
+89
View File
@@ -0,0 +1,89 @@
"""自动清理 Django 模型 ImageField/FileField 文件的信号。
当:
1. 模型实例被删除时(post_delete)
2. 字段值被更改、旧文件不再被引用时(post_save 对比 pre_save 缓存的旧值)
尝试删除磁盘上的旧文件(忽略失败、忽略不存在)。
"""
import os
from django.db import models
from django.db.models.signals import post_delete, pre_save, post_save
from django.dispatch import receiver
_MODEL_CACHE = {} # 防止多次注册同一模型
def _get_all_file_fields(model_cls):
"""返回模型中所有的 FileField/ImageField 字段名。"""
return [
f.attname for f in model_cls._meta.get_fields()
if isinstance(f, models.FileField) and f.attname
]
def _safe_delete_file(file_field_instance):
"""安全地删除 FileField 引用的磁盘文件,忽略失败。"""
try:
if file_field_instance and file_field_instance.name:
path = file_field_instance.path
if path and os.path.isfile(path):
os.remove(path)
except (OSError, ValueError):
pass
def _register_cleanup_signals():
"""注册所有已注册的 Django 应用中带 FileField/ImageField 的模型的清理信号。
幂等:同一模型多次调用只会注册一次。
"""
from django.apps import apps as django_apps
for model in django_apps.get_models():
if model in _MODEL_CACHE:
continue
file_fields = _get_all_file_fields(model)
if not file_fields:
_MODEL_CACHE[model] = None
continue
_MODEL_CACHE[model] = file_fields
# 1. post_delete: 实例删除后删除所有文件
def make_post_delete_handler(ffields):
@receiver(post_delete, sender=model, weak=False, dispatch_uid=f'cleanup_postdel_{model._meta.label}')
def handler(sender, instance, **kwargs):
for field_name in ffields:
_safe_delete_file(getattr(instance, field_name, None))
return handler
make_post_delete_handler(file_fields)
# 2. pre_save: 缓存旧值
@receiver(pre_save, sender=model, weak=False, dispatch_uid=f'cleanup_presave_{model._meta.label}')
def presave_cache(sender, instance, **kwargs):
# 不是新建的情况下,缓存数据库中该记录的旧 FileField 值
if not instance.pk:
instance.__old_filefield_values = None
return
try:
old = sender.objects.get(pk=instance.pk)
instance.__old_filefield_values = {
fn: getattr(old, fn, None) for fn in file_fields
}
except sender.DoesNotExist:
instance.__old_filefield_values = None
# 3. post_save: 对比新旧值并删除不再引用的旧文件
@receiver(post_save, sender=model, weak=False, dispatch_uid=f'cleanup_postsave_{model._meta.label}')
def postsave_cleanup(sender, instance, **kwargs):
old_vals = getattr(instance, '__old_filefield_values', None)
if not old_vals:
return
for field_name in file_fields:
old_file = old_vals.get(field_name)
new_file = getattr(instance, field_name, None)
if old_file and old_file.name:
if not new_file or new_file.name != old_file.name:
_safe_delete_file(old_file)
+49 -3
View File
@@ -1,11 +1,57 @@
from django import template
from django.utils.translation import get_language
from django.conf import settings
register = template.Library()
@register.simple_tag
def ml_field(obj, field_name):
def _ml_value(obj, field_name):
"""根据当前语言返回 obj 的 <field_name>_zh 或 <field_name>_en 字段值。"""
if obj is None:
return ''
lang = get_language()
suffix = 'en' if lang.startswith('en') else 'zh'
return getattr(obj, f'{field_name}_{suffix}', '') or getattr(obj, f'{field_name}_zh', '')
val = getattr(obj, f'{field_name}_{suffix}', '') or ''
if not val:
# 找不到对应语言内容时回退到中文
val = getattr(obj, f'{field_name}_zh', '') or ''
return val
@register.simple_tag
def ml_field(obj, field_name):
return _ml_value(obj, field_name)
@register.filter
def ml(obj, field_name):
"""过滤器形式,可在 with、变量赋值、管道中使用。
用法:
{% with about_content=site_settings|ml:'about_content' %}
{{ site_settings|ml:'site_name' }}
"""
return _ml_value(obj, field_name)
@register.filter
def strip_lang_prefix(path):
"""去掉 URL 路径中的语言前缀。
用于语言切换按钮的 next 字段:传递不带语言前缀的路径,
让 Django 的 translate_url 只需加前缀,避免 prefix_default_language=False
时去前缀失败的问题。
用法:
<input type="hidden" name="next" value="{{ request.get_full_path|strip_lang_prefix }}">
"""
if not path:
return '/'
# 去掉开头的斜杠后按 / 分割
parts = path.lstrip('/').split('/', 1)
# 检查第一段是否是已配置的语言代码
configured_langs = {code for code, _ in settings.LANGUAGES}
if parts[0] in configured_langs:
# 去掉语言前缀,返回剩余路径
return '/' + parts[1] if len(parts) > 1 else '/'
return path
+256
View File
@@ -0,0 +1,256 @@
msgid ""
msgstr ""
"Project-Id-Version: TGOIM Company Website\n"
"Report-Msgid-Bugs-To: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: en\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: templates/contact/index.html
msgid "联系方式"
msgstr "Contact Information"
msgid "如有任何问题,欢迎随时与我们联系"
msgstr "If you have any questions, please feel free to contact us"
msgid "公司名称"
msgstr "Company Name"
msgid "公司地址"
msgstr "Company Address"
msgid "联系电话"
msgstr "Phone"
msgid "电子邮箱"
msgstr "Email"
msgid "微信扫码联系"
msgstr "Scan WeChat to Contact"
msgid "在线留言"
msgstr "Leave a Message"
msgid "请填写以下信息,我们会尽快与您联系"
msgstr "Please fill in the form below and we will contact you soon"
msgid "提交留言"
msgstr "Submit Message"
#: templates/errors/404.html
msgid "页面未找到"
msgstr "Page Not Found"
msgid "您访问的页面不存在或已被删除"
msgstr "The page you are looking for does not exist or has been removed"
msgid "返回首页"
msgstr "Back to Home"
#: templates/errors/500.html
msgid "服务器错误"
msgstr "Server Error"
msgid "服务器发生了错误,请稍后再试"
msgstr "An error occurred on the server. Please try again later."
#: templates/core/home.html
msgid "了解更多"
msgstr "Learn More"
msgid "核心产品"
msgstr "Core Products"
msgid "为客户提供高品质的产品与解决方案"
msgstr "Providing customers with high-quality products and solutions"
msgid "查看详情"
msgstr "View Details"
msgid "查看全部产品"
msgstr "View All Products"
msgid "暂无产品数据"
msgstr "No products available"
#: templates/core/about.html
msgid "关于我们"
msgstr "About Us"
msgid "年行业经验"
msgstr "Years of Industry Experience"
msgid "合作客户"
msgstr "Partner Clients"
msgid "核心优势"
msgstr "Core Advantages"
msgid "技术创新"
msgstr "Technical Innovation"
msgid "持续投入研发,拥有多项核心技术专利"
msgstr "Continuous R&D investment with multiple core technology patents"
msgid "品质保证"
msgstr "Quality Assurance"
msgid "严格的质量管理体系,产品稳定可靠"
msgstr "Strict quality management system, stable and reliable products"
msgid "专业服务"
msgstr "Professional Service"
msgid "专业的技术团队,提供全方位服务支持"
msgstr "Professional technical team providing comprehensive service support"
#: templates/news/list.html
msgid "新闻分类"
msgstr "News Categories"
msgid "全部新闻"
msgstr "All News"
msgid "置顶"
msgstr "Top"
msgid "阅读全文"
msgstr "Read More"
msgid "暂无新闻数据"
msgstr "No news available"
#: templates/news/detail.html
msgid "相关新闻"
msgstr "Related News"
#: templates/solutions/list.html
msgid "方案分类"
msgstr "Solution Categories"
msgid "全部方案"
msgstr "All Solutions"
msgid "暂无方案数据"
msgstr "No solutions available"
#: templates/solutions/detail.html
msgid "方案视频"
msgstr "Solution Video"
msgid "相关方案"
msgstr "Related Solutions"
msgid "查看"
msgstr "View"
#: templates/customers/map.html
msgid "客户分布"
msgstr "Customer Distribution"
msgid "我们的客户遍布全国各地"
msgstr "Our customers are distributed across the country"
msgid "客户列表"
msgstr "Customer List"
#: templates/includes/header.html
msgid "首页"
msgstr "Home"
msgid "产品中心"
msgstr "Products"
msgid "客户案例"
msgstr "Customers"
msgid "联系我们"
msgstr "Contact Us"
#: templates/includes/footer.html
msgid "快速链接"
msgstr "Quick Links"
msgid "解决方案"
msgstr "Solutions"
msgid "新闻中心"
msgstr "News"
msgid "产品与服务"
msgstr "Products & Services"
msgid "全部产品"
msgstr "All Products"
msgid "关注我们"
msgstr "Follow Us"
#: templates/products/list.html
msgid "产品分类"
msgstr "Product Categories"
#: templates/products/detail.html
msgid "型号"
msgstr "Model"
msgid "产品特点"
msgstr "Product Features"
msgid "咨询购买"
msgstr "Inquire & Buy"
msgid "资料下载"
msgstr "Download Datasheet"
msgid "产品视频"
msgstr "Product Video"
msgid "产品描述"
msgstr "Product Description"
msgid "技术参数"
msgstr "Technical Specifications"
msgid "相关产品"
msgstr "Related Products"
#: templates/admin/core/deploylog/detail.html
msgid "执行中"
msgstr "Running"
msgid "成功"
msgstr "Success"
msgid "失败"
msgstr "Failed"
msgid "触发者"
msgstr "Triggered by"
msgid "开始"
msgstr "Started"
msgid "结束"
msgstr "Finished"
msgid "耗时"
msgstr "Duration"
msgid "刷新查看进度"
msgstr "Refresh to View Progress"
msgid "返回列表"
msgstr "Back to List"
msgid "再次部署"
msgstr "Deploy Again"
#: templates/admin/core/deploylog/change_list.html
msgid "部署进行中…"
msgstr "Deployment in progress…"
msgid "一键部署更新"
msgstr "One-Click Deploy"
+3 -3
View File
@@ -70,7 +70,7 @@ a:hover { color: var(--primary-dark); }
.section-title h2 { margin-bottom: 0.75rem; }
.section-title p { color: var(--text-secondary); margin-bottom: 0; }
.banner-carousel .carousel-item { height: 650px; background: #000; }
.banner-carousel .carousel-item { height: 750px; background: #000; }
.banner-carousel .carousel-item img { width: 100%; height: 100%; object-fit: cover; opacity: 0.85; }
.banner-carousel .carousel-caption { bottom: 25%; text-align: left; }
.banner-carousel .carousel-caption h1 { font-size: 2.5rem; margin-bottom: 1rem; }
@@ -261,13 +261,13 @@ a:hover { color: var(--primary-dark); }
.contact-form textarea.form-control { resize: vertical; min-height: 120px; }
@media (max-width: 991.98px) {
.banner-carousel .carousel-item { height: 480px; }
.banner-carousel .carousel-item { height: 560px; }
.banner-carousel .carousel-caption h1 { font-size: 1.75rem; }
.section { padding: 2.5rem 0; }
}
@media (max-width: 767.98px) {
.banner-carousel .carousel-item { height: 380px; }
.banner-carousel .carousel-item { height: 440px; }
.banner-carousel .carousel-caption { bottom: 20%; text-align: center; left: 10%; right: 10%; }
.banner-carousel .carousel-caption h1 { font-size: 1.25rem; }
.banner-carousel .carousel-caption p { font-size: 0.875rem; margin-bottom: 1rem; }
@@ -0,0 +1,23 @@
{% extends "admin/change_list.html" %}
{% load i18n %}
{% block object-tools-items %}
{% if deploy_url %}
{% if has_running %}
<li>
<span style="display:inline-block;padding:8px 12px;color:#999;cursor:not-allowed;">
{% trans '部署进行中…' %}
</span>
</li>
{% else %}
<li>
<a href="{{ deploy_url }}" class="addlink"
style="background-color:#165DFF;color:#fff;"
onclick="return confirm('确认从 Git 拉取最新代码并重启服务吗?\n\n执行步骤:\n1. git pull\n2. pip install\n3. migrate\n4. collectstatic\n5. supervisorctl restart');">
{% trans '一键部署更新' %}
</a>
</li>
{% endif %}
{% endif %}
{{ block.super }}
{% endblock %}
+110
View File
@@ -0,0 +1,110 @@
{% extends "admin/base_site.html" %}
{% load i18n %}
{% block extrastyle %}
{{ block.super }}
<style>
.deploy-header {
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 16px;
flex-wrap: wrap;
}
.deploy-status {
display: inline-block;
padding: 4px 12px;
border-radius: 4px;
font-weight: 600;
font-size: 0.9rem;
}
.deploy-status.running { background: #fff7e6; color: #d46b08; }
.deploy-status.success { background: #f6ffed; color: #389e0d; }
.deploy-status.failed { background: #fff1f0; color: #cf1322; }
.deploy-meta {
color: #666;
font-size: 0.9rem;
margin-bottom: 12px;
}
.deploy-output {
background: #1e1e1e;
color: #d4d4d4;
font-family: "Consolas", "Monaco", "Courier New", monospace;
font-size: 0.85rem;
line-height: 1.5;
padding: 16px;
border-radius: 6px;
white-space: pre-wrap;
word-break: break-all;
max-height: 600px;
overflow-y: auto;
border: 1px solid #333;
}
.deploy-actions { margin-top: 16px; }
.deploy-actions a {
display: inline-block;
padding: 8px 16px;
background: #165DFF;
color: #fff;
border-radius: 4px;
text-decoration: none;
margin-right: 8px;
font-size: 0.9rem;
}
.deploy-actions a:hover { background: #0E42D2; }
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid #d46b08;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
vertical-align: middle;
margin-right: 6px;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
{% endblock %}
{% block content %}
<div class="deploy-header">
<h1 style="margin:0;">{{ title }}</h1>
{% if log.status == 'running' %}
<span class="deploy-status running">
<span class="spinner"></span>{% trans '执行中' %}
</span>
{% elif log.status == 'success' %}
<span class="deploy-status success">{% trans '成功' %}</span>
{% elif log.status == 'failed' %}
<span class="deploy-status failed">{% trans '失败' %}</span>
{% endif %}
</div>
<div class="deploy-meta">
{% if log.triggered_by %}{% trans '触发者' %}: {{ log.triggered_by.username }} · {% endif %}
{% trans '开始' %}: {{ log.started_at|date:"Y-m-d H:i:s" }}
{% if log.finished_at %} · {% trans '结束' %}: {{ log.finished_at|date:"Y-m-d H:i:s" }} · {% trans '耗时' %}: {{ log.duration }}{% endif %}
</div>
<div class="deploy-output" id="deploy-output">{{ log.output|default:'(暂无输出)' }}</div>
<div class="deploy-actions">
{% if is_running %}
<a href="" onclick="location.reload();return false;">{% trans '刷新查看进度' %}</a>
{% else %}
<a href="{% url 'admin:core_deploylog_changelist' %}">{% trans '返回列表' %}</a>
<a href="{% url 'admin:core_deploy_trigger' %}"
onclick="return confirm('确认从 Git 拉取最新代码并重启服务吗?');">
{% trans '再次部署' %}
</a>
{% endif %}
</div>
{% if is_running %}
<script>
// 自动刷新:每 3 秒拉取最新日志
setTimeout(function() { location.reload(); }, 3000);
</script>
{% endif %}
{% endblock %}
@@ -0,0 +1,339 @@
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}
{{ block.super }}
<style>
.mf-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
flex-wrap: wrap;
gap: 12px;
}
.mf-stats {
display: flex;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 20px;
}
.mf-stat-card {
flex: 1;
min-width: 180px;
padding: 14px 18px;
background: #fff;
border-radius: 8px;
border: 1px solid #e5e6eb;
box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.mf-stat-card .label { color: #86909c; font-size: 0.85rem; }
.mf-stat-card .value { font-size: 1.4rem; font-weight: 600; color: #1d2129; margin-top: 4px; }
.mf-path-bar {
padding: 10px 16px;
background: #f7f8fa;
border-radius: 6px;
margin-bottom: 16px;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
font-size: 0.9rem;
}
.mf-path-bar a { color: #165DFF; text-decoration: none; }
.mf-path-bar a:hover { text-decoration: underline; }
.mf-path-bar .sep { color: #c9cdd4; }
.mf-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 12px;
margin-top: 16px;
}
.mf-item {
background: #fff;
border: 1px solid #e5e6eb;
border-radius: 8px;
overflow: hidden;
transition: box-shadow .2s, transform .2s;
display: flex;
flex-direction: column;
position: relative;
}
.mf-item:hover {
box-shadow: 0 4px 16px rgba(0,0,0,0.1);
transform: translateY(-2px);
}
.mf-item.dir { background: #fff7e6; border-color: #ffd591; }
.mf-thumb {
width: 100%;
aspect-ratio: 1;
background: #f7f8fa center/contain no-repeat;
display: flex;
align-items: center;
justify-content: center;
font-size: 2.5rem;
position: relative;
}
.mf-thumb.dir-thumb { background: #fff1b8; }
.mf-info {
padding: 8px 10px;
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
}
.mf-name {
font-size: 0.85rem;
color: #1d2129;
word-break: break-all;
line-height: 1.3;
max-height: 2.6em;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.mf-meta { font-size: 0.75rem; color: #86909c; }
.mf-actions {
display: flex;
border-top: 1px solid #f2f3f5;
}
.mf-actions a, .mf-actions button {
flex: 1;
padding: 6px;
font-size: 0.78rem;
text-align: center;
border: none;
cursor: pointer;
background: #fff;
color: #165DFF;
text-decoration: none;
border-right: 1px solid #f2f3f5;
}
.mf-actions a:last-child, .mf-actions button:last-child { border-right: none; }
.mf-actions button.delete { color: #f53f3f; }
.mf-actions a:hover, .mf-actions button:hover { background: #f7f8fa; }
.mf-actions button.delete:hover { background: #ffecec; }
.mf-actions a:only-child { border-right: none; }
.mf-empty {
text-align: center;
padding: 60px 20px;
color: #86909c;
background: #fff;
border: 1px dashed #e5e6eb;
border-radius: 8px;
}
.mf-preview-mask {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.75);
display: none;
align-items: center;
justify-content: center;
z-index: 9999;
padding: 40px;
}
.mf-preview-mask.show { display: flex; }
.mf-preview-box {
max-width: 90%;
max-height: 90%;
background: #fff;
padding: 12px;
border-radius: 8px;
position: relative;
display: flex;
flex-direction: column;
}
.mf-preview-box img {
max-width: 80vw;
max-height: 70vh;
object-fit: contain;
}
.mf-preview-box iframe {
border: 1px solid #e5e6eb;
border-radius: 4px;
}
.mf-preview-close {
position: absolute;
top: -36px; right: 0;
background: #fff;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.mf-preview-path {
margin-top: 8px;
font-size: 0.85rem;
color: #86909c;
word-break: break-all;
}
.mf-notice {
padding: 12px 16px;
background: #e8f0ff;
color: #0e42d2;
border-radius: 6px;
border-left: 3px solid #165DFF;
margin-bottom: 16px;
font-size: 0.9rem;
}
.mf-notice strong { color: #165DFF; }
</style>
{% endblock %}
{% block content %}
<div class="mf-header">
<h1 style="margin:0;">{{ title }}</h1>
<div style="color:#86909c;">共占用:<strong style="color:#1d2129;">{{ usage.total }}</strong></div>
</div>
<div class="mf-notice">
<strong>说明:</strong>这里可以浏览和删除所有媒体目录的文件(包括富文本编辑器上传的图片、产品图片、轮播图等)。
删除文件前请确认其不再被任何页面引用,否则页面会显示破图。
<strong>uploads/</strong> 目录存放的是富文本编辑器(CKEditor)上传的图片。
</div>
<div class="mf-stats">
{% for d in usage.top_dirs %}
<div class="mf-stat-card">
<div class="label">{{ d.name }}</div>
<div class="value">{{ d.size }}</div>
<div style="font-size:0.8rem;color:#86909c;margin-top:4px;">{{ d.count }} 个文件</div>
</div>
{% empty %}
<div class="mf-stat-card" style="grid-column:1/-1;">
<div class="label">暂无数据</div>
<div class="value">-</div>
</div>
{% endfor %}
</div>
<div class="mf-path-bar">
<a href="{{ list_url }}">📁 根目录</a>
{% for crumb in data.breadcrumb %}
<span class="sep">/</span>
<a href="{{ list_url }}?path={{ crumb.path }}">{{ crumb.name }}</a>
{% endfor %}
</div>
{% if data.parent_path != None %}
<a href="{{ list_url }}?path={{ data.parent_path }}" style="display:inline-block;margin-bottom:8px;">⬆ 返回上级</a>
{% endif %}
{% if data.subdirs or data.files %}
<div class="mf-grid">
{% for d in data.subdirs %}
<div class="mf-item dir">
<a href="{{ list_url }}?path={{ d.path }}" class="mf-thumb dir-thumb" title="进入目录" style="text-decoration:none;color:#d46b08;">
📁
</a>
<div class="mf-info">
<div class="mf-name"><strong>{{ d.name }}</strong></div>
<div class="mf-meta">{{ d.file_count }} 个 · {{ d.size }}</div>
</div>
<div class="mf-actions">
<a href="{{ list_url }}?path={{ d.path }}">打开</a>
</div>
</div>
{% endfor %}
{% for f in data.files %}
<div class="mf-item" data-path="{{ f.path }}">
<div class="mf-thumb"
{% if f.is_image %}style="background-image:url('{{ f.url }}');"{% endif %}
onclick="{% if f.is_image %}showPreview('{{ f.url }}', '{{ f.path }}', '{{ f.size }}');{% endif %}">
{% if not f.is_image %}
{% if f.name|slice:"-4:" == ".pdf" %}📄{% elif f.name|slice:"-4:" == ".mp4" or f.name|slice:"-4:" == ".webm" %}🎬{% else %}📎{% endif %}
{% endif %}
</div>
<div class="mf-info">
<div class="mf-name" title="{{ f.name }}">{{ f.name }}</div>
<div class="mf-meta">{{ f.size }}</div>
</div>
<div class="mf-actions">
{% if f.is_image %}
<a href="{{ f.url }}" target="_blank">原图</a>
{% else %}
<a href="{{ f.url }}" target="_blank">下载</a>
{% endif %}
<button class="delete" onclick="confirmDelete('{{ f.path }}', this)">删除</button>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="mf-empty">
📂 此目录为空
</div>
{% endif %}
{# 图片预览 #}
<div class="mf-preview-mask" id="previewMask" onclick="if(event.target===this)closePreview();">
<div class="mf-preview-box">
<button class="mf-preview-close" onclick="closePreview();">✕ 关闭</button>
<img id="previewImg" alt="" src="">
<div class="mf-preview-path">
路径:<span id="previewPath"></span>
<span id="previewSize"></span>
</div>
</div>
</div>
<script>
const deleteUrl = '{{ delete_url }}';
const listUrl = '{{ list_url }}';
const currentDir = '{{ data.current_path }}';
function confirmDelete(path, btn) {
const name = path.split('/').pop();
if (!confirm(`确定要删除文件 "${name}" 吗?\n\n路径:${path}\n\n删除后不可恢复!`)) return;
btn.disabled = true;
btn.textContent = '删除中...';
const fd = new FormData();
fd.append('path', path);
fd.append('csrfmiddlewaretoken', '{{ csrf_token }}');
fetch(deleteUrl, {
method: 'POST',
body: fd,
headers: {'X-Requested-With': 'XMLHttpRequest'},
}).then(r => r.json()).then(resp => {
if (resp.ok) {
const item = btn.closest('.mf-item');
item.style.transition = 'opacity .3s, transform .3s';
item.style.opacity = '0';
item.style.transform = 'scale(0.8)';
setTimeout(() => item.remove(), 280);
} else {
alert('删除失败:' + resp.msg);
btn.disabled = false;
btn.textContent = '删除';
}
}).catch(() => {
alert('网络错误,请刷新后重试');
btn.disabled = false;
btn.textContent = '删除';
});
}
function showPreview(url, path, size) {
document.getElementById('previewImg').src = url;
document.getElementById('previewPath').textContent = path;
document.getElementById('previewSize').textContent = ' · ' + size;
document.getElementById('previewMask').classList.add('show');
}
function closePreview() {
document.getElementById('previewMask').classList.remove('show');
document.getElementById('previewImg').src = '';
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closePreview(); });
</script>
{% endblock %}
+13
View File
@@ -6,6 +6,15 @@
{% block content %}
<section class="section bg-white py-5">
<div class="container">
<div class="section-title">
<h2>{% trans '关于我们' %}</h2>
</div>
{% with about_content=site_settings|ml:'about_content' %}
{% if about_content %}
<div class="about-content">
{{ about_content|safe }}
</div>
{% else %}
<div class="row align-items-center g-5">
<div class="col-lg-6">
<h2 class="mb-4">{% trans '关于我们' %}</h2>
@@ -36,9 +45,12 @@
</div>
</div>
</div>
{% endif %}
{% endwith %}
</div>
</section>
{% if not site_settings.about_content_zh and not site_settings.about_content_en and not about_content %}
<section class="section">
<div class="container">
<div class="section-title">
@@ -69,4 +81,5 @@
</div>
</div>
</section>
{% endif %}
{% endblock %}
+1 -1
View File
@@ -44,7 +44,7 @@
<div class="col-lg-4 col-md-6">
<div class="card h-100">
{% if product.main_image %}
<img src="{{ product.main_image.url }}" class="card-img-top" alt="{% ml_field product 'name' %}" style="height: 220px; object-fit: cover;">
<img src="{{ product.main_image.url }}" class="card-img-top" alt="{% ml_field product 'name' %}" style="height: 260px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">
{% endif %}
<div class="card-body">
<h5 class="card-title">{% ml_field product 'name' %}</h5>
+1 -1
View File
@@ -31,7 +31,7 @@
</ul>
<form action="{% url 'set_language' %}" method="post" class="lang-switcher ms-lg-3 mt-2 mt-lg-0">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path }}">
<input type="hidden" name="next" value="{{ request.get_full_path|strip_lang_prefix|force_escape }}">
<button type="submit" name="language" value="zh-hans" class="btn btn-sm {% if LANGUAGE_CODE == 'zh-hans' %}btn-primary{% else %}btn-outline-primary{% endif %}">中文</button>
<button type="submit" name="language" value="en" class="btn btn-sm {% if LANGUAGE_CODE == 'en' %}btn-primary{% else %}btn-outline-primary{% endif %}">EN</button>
</form>
+1 -1
View File
@@ -34,7 +34,7 @@
<div class="row g-0">
{% if n.cover_image %}
<div class="col-4">
<img src="{{ n.cover_image.url }}" class="img-fluid rounded-start h-100" alt="{% ml_field n 'title' %}" style="object-fit: cover; min-height: 100px;">
<img src="{{ n.cover_image.url }}" class="img-fluid rounded-start w-100" alt="{% ml_field n 'title' %}" style="height: 110px; object-fit: contain; background: #f7f8fa; padding: 0.25rem;">
</div>
{% endif %}
<div class="{% if n.cover_image %}col-8{% else %}col-12{% endif %}">
+1 -1
View File
@@ -24,7 +24,7 @@
<div class="row g-0">
{% if news.cover_image %}
<div class="col-md-3">
<img src="{{ news.cover_image.url }}" class="img-fluid rounded-start h-100" alt="{% ml_field news 'title' %}" style="object-fit: cover; min-height: 180px;">
<img src="{{ news.cover_image.url }}" class="img-fluid rounded-start w-100" alt="{% ml_field news 'title' %}" style="height: 180px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">
</div>
{% endif %}
<div class="{% if news.cover_image %}col-md-9{% else %}col-12{% endif %}">
+1 -1
View File
@@ -91,7 +91,7 @@
{% for p in related %}
<div class="col-lg-3 col-md-4 col-6">
<div class="card h-100">
{% if p.main_image %}<img src="{{ p.main_image.url }}" class="card-img-top" alt="{% ml_field p 'name' %}" style="height: 140px; object-fit: cover;">{% endif %}
{% if p.main_image %}<img src="{{ p.main_image.url }}" class="card-img-top" alt="{% ml_field p 'name' %}" style="height: 160px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">{% endif %}
<div class="card-body p-3">
<h6 class="card-title small">{% ml_field p 'name' %}</h6>
<a href="{% url 'product_detail' p.slug %}" class="btn btn-sm btn-outline-primary w-100">{% trans '查看' %}</a>
+1 -1
View File
@@ -24,7 +24,7 @@
<div class="col-lg-4 col-md-6">
<div class="card h-100">
{% if product.main_image %}
<img src="{{ product.main_image.url }}" class="card-img-top" alt="{% ml_field product 'name' %}" style="height: 200px; object-fit: cover;">
<img src="{{ product.main_image.url }}" class="card-img-top" alt="{% ml_field product 'name' %}" style="height: 240px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">
{% endif %}
<div class="card-body">
<h6 class="card-title">{% ml_field product 'name' %}</h6>
+1 -1
View File
@@ -40,7 +40,7 @@
{% for s in related %}
<div class="col-lg-3 col-md-4 col-6">
<div class="card h-100">
{% if s.cover_image %}<img src="{{ s.cover_image.url }}" class="card-img-top" alt="{% ml_field s 'title' %}" style="height: 140px; object-fit: cover;">{% endif %}
{% if s.cover_image %}<img src="{{ s.cover_image.url }}" class="card-img-top" alt="{% ml_field s 'title' %}" style="height: 160px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">{% endif %}
<div class="card-body p-3">
<h6 class="card-title small">{% ml_field s 'title' %}</h6>
<a href="{% url 'solution_detail' s.slug %}" class="btn btn-sm btn-outline-primary w-100">{% trans '查看' %}</a>
+1 -1
View File
@@ -24,7 +24,7 @@
<div class="col-lg-6">
<div class="card h-100">
{% if solution.cover_image %}
<img src="{{ solution.cover_image.url }}" class="card-img-top" alt="{% ml_field solution 'title' %}" style="height: 220px; object-fit: cover;">
<img src="{{ solution.cover_image.url }}" class="card-img-top" alt="{% ml_field solution 'title' %}" style="height: 260px; object-fit: contain; background: #f7f8fa; padding: 0.5rem;">
{% endif %}
<div class="card-body">
<h5 class="card-title">{% ml_field solution 'title' %}</h5>
+61
View File
@@ -418,6 +418,67 @@ curl -I http://127.0.0.1/ --header "Host: www.tgoim.com"
### 10.1 更新代码
#### 方式一:后台一键部署(推荐)
网站后台已集成"在线部署"功能,可在浏览器中一键从 Git 拉取最新代码并自动完成更新,无需登录服务器。
**使用步骤:**
1. 登录后台管理 `https://www.tgoim.com/admin/`
2. 在左侧菜单进入「部署日志」(核心 → 部署日志)
3. 点击右上角「一键部署更新」按钮
4. 在确认对话框中点击「确定」
5. 页面会跳转到日志详情页,每 3 秒自动刷新显示部署进度
6. 部署完成后会自动重启服务
**部署流程会依次执行:**
1. `git pull origin main` 拉取最新代码
2. `pip install -r requirements.txt` 安装/更新依赖
3. `python manage.py migrate` 执行数据库迁移
4. `python manage.py collectstatic --noinput` 收集静态文件
5. `sudo supervisorctl restart tgoim` 重启服务
**前置条件(一次性配置):**
为了让运行 Django 的 `www-data` 用户能够执行 `git pull` 和重启服务,需要配置 sudoers 允许其无密码执行特定命令。在服务器上执行:
```bash
# 创建 sudoers 配置,允许 www-data 无密码执行 supervisorctl
sudo cat > /etc/sudoers.d/tgoim-deploy << 'EOF'
# 允许 www-data 无密码重启 tgoim 服务(用于在线部署)
www-data ALL=(root) NOPASSWD: /usr/bin/supervisorctl restart tgoim
www-data ALL=(root) NOPASSWD: /usr/bin/supervisorctl status tgoim
EOF
# 设置正确的权限
sudo chmod 440 /etc/sudoers.d/tgoim-deploy
# 验证配置语法(重要!避免 sudo 配置错误导致系统问题)
sudo visudo -c
```
**Git 仓库权限配置:**
确保 `www-data` 用户对项目目录有足够的权限执行 git pull:
```bash
# 设置项目目录所有者为 www-data
sudo chown -R www-data:www-data /opt/company_website
# 确保数据库和媒体目录可写
sudo chown www-data:www-data /opt/company_website/db.sqlite3
sudo chown -R www-data:www-data /opt/company_website/media
sudo chown -R www-data:www-data /opt/company_website/staticfiles
```
**注意事项:**
- 部署过程中请勿同时登录服务器手动执行 `git pull`,以免冲突
- 系统会自动防止并发部署(已有任务运行时按钮会禁用)
- 如果自动重启失败,日志会提示手动执行命令,按提示操作即可
- 所有部署操作会记录在「部署日志」中,可随时查看历史
#### 方式二:手动命令行部署
```bash
cd /opt/company_website