如何在Django CKEditor中设置图片最大尺寸?
在django-ckeditor中设置图片最大尺寸的方法
首先要明确:CKEDITOR_THUMBNAIL_SIZE仅用于设置后台文件管理器中图片的缩略图尺寸,不会限制上传原图的大小,这就是你之前配置后没生效的原因。下面提供几种可行的解决方案:
1. 前端配置限制(基础防误操作)
在settings.py的CKEDITOR_CONFIGS中添加图片上传的尺寸和大小限制,这会在CKEditor的上传界面做前端校验:
CKEDITOR_CONFIGS = { 'default': { # 保留你原有的其他配置 'filebrowserImageUploadSettings': { 'maxWidth': 1920, # 允许的图片最大宽度 'maxHeight': 1080, # 允许的图片最大高度 'maxSize': 5 * 1024 * 1024, # 允许的最大文件大小(5MB) }, } }
注意:前端限制可以被绕过,所以必须配合后端验证更安全。
2. 后端验证上传图片尺寸
在模型保存前校验图片尺寸,不符合则抛出错误:
from django.db import models from django.core.exceptions import ValidationError from ckeditor_uploader.fields import RichTextUploadingField from PIL import Image import re import os from django.conf import settings class Post(models.Model): text = RichTextUploadingField(max_length=1050, null=True, blank=True) def clean(self): super().clean() # 从富文本中提取图片路径 img_pattern = re.compile(r'<img[^>]+src="([^"]+)"') img_srcs = img_pattern.findall(self.text or '') for src in img_srcs: # 转换为本地文件路径 img_path = os.path.join(settings.MEDIA_ROOT, src.lstrip('/media/')) if os.path.exists(img_path): with Image.open(img_path) as img: width, height = img.size # 设置允许的最大尺寸 if width > 1920 or height > 1080: raise ValidationError(f"图片尺寸超出限制,最大允许1920×1080,当前图片为{width}×{height}")
3. 自动调整上传图片大小(替代限制)
如果不想阻止上传,而是自动将过大的图片压缩到指定尺寸,可以自定义上传处理函数:
步骤1:编写自定义上传视图
from ckeditor_uploader.views import upload from django.http import JsonResponse from PIL import Image import os from django.conf import settings def custom_image_upload(request): # 调用原CKEditor上传逻辑 response = upload(request) if response.status_code == 200: data = response.json() if 'url' in data: img_url = data['url'] img_path = os.path.join(settings.MEDIA_ROOT, img_url.lstrip('/media/')) with Image.open(img_path) as img: max_width, max_height = 1920, 1080 width, height = img.size if width > max_width or height > max_height: # 计算等比例缩放的尺寸 scale_ratio = min(max_width/width, max_height/height) new_size = (int(width*scale_ratio), int(height*scale_ratio)) # 高质量缩放图片 img = img.resize(new_size, Image.Resampling.LANCZOS) # 保存压缩后的图片(保留85%质量) img.save(img_path, quality=85) return JsonResponse(data) return response
步骤2:替换原CKEditor上传URL
在项目的urls.py中覆盖默认的上传路由:
from django.urls import path from .views import custom_image_upload urlpatterns = [ # 其他路由... path('ckeditor/upload/', custom_image_upload, name='ckeditor_upload'), ]
内容的提问来源于stack exchange,提问作者AntonisT
相关产品推荐
相关产品推荐

