1. 增加服务器图片管理
This commit is contained in:
+133
-1
@@ -1,12 +1,17 @@
|
|||||||
|
from pathlib import Path
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
from django.http import JsonResponse
|
||||||
from django.shortcuts import redirect, render
|
from django.shortcuts import redirect, render
|
||||||
from django.urls import path, reverse
|
from django.urls import path, reverse
|
||||||
from django.utils.html import format_html
|
from django.utils.html import format_html
|
||||||
from django.contrib import messages
|
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 ckeditor_uploader.widgets import CKEditorUploadingWidget
|
||||||
from .models import SiteSettings, Banner, DeployLog
|
from .models import SiteSettings, Banner, DeployLog, MediaFile
|
||||||
from .deploy import start_deploy
|
from .deploy import start_deploy
|
||||||
|
from . import file_manager as fm
|
||||||
|
|
||||||
|
|
||||||
@admin.register(SiteSettings)
|
@admin.register(SiteSettings)
|
||||||
@@ -145,3 +150,130 @@ class DeployLogAdmin(admin.ModelAdmin):
|
|||||||
extra_context['deploy_url'] = reverse('admin:core_deploy_trigger')
|
extra_context['deploy_url'] = reverse('admin:core_deploy_trigger')
|
||||||
extra_context['has_running'] = DeployLog.objects.filter(status='running').exists()
|
extra_context['has_running'] = DeployLog.objects.filter(status='running').exists()
|
||||||
return super().changelist_view(request, extra_context)
|
return super().changelist_view(request, extra_context)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------
|
||||||
|
# 媒体文件管理:通过一个 managed=False 的虚拟模型挂到左侧侧栏
|
||||||
|
# ---------------------------------------------------------------
|
||||||
|
|
||||||
|
@admin.register(MediaFile)
|
||||||
|
class MediaFileAdmin(admin.ModelAdmin):
|
||||||
|
"""代理 Admin:点击侧栏"媒体文件"时跳转到自定义文件管理器页面。
|
||||||
|
|
||||||
|
该模型 managed=False,不访问数据库,默认权限被禁用。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def has_module_permission(self, request):
|
||||||
|
# 只有超级管理员或明确有 core.manage_files 权限才可见
|
||||||
|
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 changelist_view(self, request, extra_context=None):
|
||||||
|
# 访问 admin/core/mediafile/ 时跳转到自定义页面
|
||||||
|
return redirect(reverse('admin:core_mediafile_changelist'))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------
|
||||||
|
# 媒体文件管理器(无模型,自定义 URL + 视图)
|
||||||
|
# ---------------------------------------------------------------
|
||||||
|
|
||||||
|
class MediaFileManagerAdmin:
|
||||||
|
"""伪 Admin 入口:只用来注入 URL 和渲染页面。
|
||||||
|
|
||||||
|
我们直接通过 admin_site 注册 custom_urls,而不是注册一个 ModelAdmin,
|
||||||
|
因为这个功能不需要数据库模型。
|
||||||
|
"""
|
||||||
|
model_name = 'mediafile'
|
||||||
|
app_label = 'core'
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get_custom_urls(cls, admin_site):
|
||||||
|
view = admin_site.admin_view(cls.changelist_view)
|
||||||
|
delete_view = admin_site.admin_view(require_POST(cls.delete_view))
|
||||||
|
preview_view = admin_site.admin_view(cls.preview_view)
|
||||||
|
|
||||||
|
return [
|
||||||
|
path('mediafiles/', view, name='core_mediafile_changelist'),
|
||||||
|
path('mediafiles/delete/', delete_view, name='core_mediafile_delete'),
|
||||||
|
path('mediafiles/preview/', preview_view, name='core_mediafile_preview'),
|
||||||
|
]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def changelist_view(request):
|
||||||
|
# 权限校验:只有超级管理员或有 manage_files 权限者可访问
|
||||||
|
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,
|
||||||
|
'list_url': reverse('admin:core_mediafile_changelist'),
|
||||||
|
'delete_url': reverse('admin:core_mediafile_delete'),
|
||||||
|
'preview_url': reverse('admin:core_mediafile_preview'),
|
||||||
|
'opts': type('FakeOpts', (), {
|
||||||
|
'verbose_name_plural': '媒体文件',
|
||||||
|
'app_label': 'core',
|
||||||
|
'model_name': 'mediafile',
|
||||||
|
})(),
|
||||||
|
}
|
||||||
|
return render(request, 'admin/core/mediafile/change_list.html', context)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def delete_view(request):
|
||||||
|
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}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def preview_view(request):
|
||||||
|
rel_path = request.GET.get('path', '').strip()
|
||||||
|
# 返回 JSON:文件 URL、路径、大小
|
||||||
|
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})
|
||||||
|
|
||||||
|
|
||||||
|
# 注入 MediaFile 的 URL 到 admin.site
|
||||||
|
# 做法:覆写 AdminSite 的 get_urls 时追加
|
||||||
|
_original_admin_get_urls = admin.AdminSite.get_urls
|
||||||
|
|
||||||
|
|
||||||
|
def _patched_admin_get_urls(self):
|
||||||
|
urls = _original_admin_get_urls(self)
|
||||||
|
urls.extend(MediaFileManagerAdmin.get_custom_urls(self))
|
||||||
|
return urls
|
||||||
|
|
||||||
|
|
||||||
|
admin.AdminSite.get_urls = _patched_admin_get_urls
|
||||||
|
|
||||||
|
|||||||
@@ -5,3 +5,8 @@ class CoreConfig(AppConfig):
|
|||||||
default_auto_field = 'django.db.models.BigAutoField'
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
name = 'apps.core'
|
name = 'apps.core'
|
||||||
verbose_name = '内容管理'
|
verbose_name = '内容管理'
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
# 注册所有 ImageField 文件的自动清理信号
|
||||||
|
from .signals import _register_cleanup_signals # noqa: F401
|
||||||
|
_register_cleanup_signals()
|
||||||
|
|||||||
@@ -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),
|
||||||
|
}
|
||||||
@@ -1,5 +1,25 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from django.db import models
|
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):
|
class SiteSettings(models.Model):
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -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 %}
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
<div class="row g-0">
|
<div class="row g-0">
|
||||||
{% if n.cover_image %}
|
{% if n.cover_image %}
|
||||||
<div class="col-4">
|
<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>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="{% if n.cover_image %}col-8{% else %}col-12{% endif %}">
|
<div class="{% if n.cover_image %}col-8{% else %}col-12{% endif %}">
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
<div class="row g-0">
|
<div class="row g-0">
|
||||||
{% if news.cover_image %}
|
{% if news.cover_image %}
|
||||||
<div class="col-md-3">
|
<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>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="{% if news.cover_image %}col-md-9{% else %}col-12{% endif %}">
|
<div class="{% if news.cover_image %}col-md-9{% else %}col-12{% endif %}">
|
||||||
|
|||||||
@@ -91,7 +91,7 @@
|
|||||||
{% for p in related %}
|
{% for p in related %}
|
||||||
<div class="col-lg-3 col-md-4 col-6">
|
<div class="col-lg-3 col-md-4 col-6">
|
||||||
<div class="card h-100">
|
<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">
|
<div class="card-body p-3">
|
||||||
<h6 class="card-title small">{% ml_field p 'name' %}</h6>
|
<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>
|
<a href="{% url 'product_detail' p.slug %}" class="btn btn-sm btn-outline-primary w-100">{% trans '查看' %}</a>
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
<div class="col-lg-4 col-md-6">
|
<div class="col-lg-4 col-md-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
{% if product.main_image %}
|
{% 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 %}
|
{% endif %}
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<h6 class="card-title">{% ml_field product 'name' %}</h6>
|
<h6 class="card-title">{% ml_field product 'name' %}</h6>
|
||||||
|
|||||||
@@ -40,7 +40,7 @@
|
|||||||
{% for s in related %}
|
{% for s in related %}
|
||||||
<div class="col-lg-3 col-md-4 col-6">
|
<div class="col-lg-3 col-md-4 col-6">
|
||||||
<div class="card h-100">
|
<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">
|
<div class="card-body p-3">
|
||||||
<h6 class="card-title small">{% ml_field s 'title' %}</h6>
|
<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>
|
<a href="{% url 'solution_detail' s.slug %}" class="btn btn-sm btn-outline-primary w-100">{% trans '查看' %}</a>
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
<div class="col-lg-6">
|
<div class="col-lg-6">
|
||||||
<div class="card h-100">
|
<div class="card h-100">
|
||||||
{% if solution.cover_image %}
|
{% 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 %}
|
{% endif %}
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<h5 class="card-title">{% ml_field solution 'title' %}</h5>
|
<h5 class="card-title">{% ml_field solution 'title' %}</h5>
|
||||||
|
|||||||
Reference in New Issue
Block a user