django-ckeditor配置html5video实现视频上传与播放
1. 手动下载插件
html5video的插件:https://github.com/bahriddin/ckeditor-html5-video
解压插件,将html5video
放到ckeditor/ckeditor/plugins
的目录里。
2. 修改ckeditor源码
1. 通过使用ckeditor->config.js->extraPlugins配置启用html5video插件
添加:
config.extraPlugins = 'html5video';
CKEDITOR.editorConfig = function( config ) {// Define changes to default configuration here. For example:// config.language = 'fr';// config.uiColor = '#AADC6E';config.allowedContent = true;config.extraPlugins = 'html5video';};
2. 将html5video加到CKEDITOR_CONFIGS里
CKEDITOR_CONFIGS = {'default': {'toolbar': 'Custom', # 工具条功能'height': 600, # 编辑器高度'width': 800, # 编辑器宽'toolbar_Custom':[['Bold', 'Italic', 'Underline'], # 粗体、斜体、下划线['Link', 'Unlink'], # 链接、取消链接['NumberedList', 'BulletedList'], # 有序、无序列表['Format'], # 格式(如标题、段落)['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], # 左对齐、居中、右对齐、两端对齐['Image', 'Html5video', 'Table', 'HorizontalRule'], # 图片、表格、分割线['Undo', 'Redo'], # 撤销、重做['Source'], # 源代码模式],'stylesSet': [{'name': '1.5 倍行距', 'element': 'p', 'attributes': {'style': 'line-height: 1.5;'}}],'extraPlugins': ['html5video', 'widget', 'widgetselection', 'clipboard', 'lineutils'],},
}
3. 前台渲染页面,video标签有播放控件
由于ckeditor渲染到页面上的代码是:
<div class="ckeditor-html5-video" style="text-align: center;">
<video controlslist="nodownload" src="/media/upload/2025/07/08/ljzy_03.mp4"> </video>
</div>
发现controlslist="nodownload"属性没有播放按钮,需要改成controls属性。
所以在渲染页面需要使用js进行修改:
<script>document.addEventListener('DOMContentLoaded', () => {const fixVideos = () => {try {const videos = document.querySelectorAll('.ckeditor-html5-video video');if (!videos.length) {console.warn('No videos found in .ckeditor-html5-video.');return;}videos.forEach((video, index) => {video.controls = true; // 添加 controlsvideo.removeAttribute('controlslist'); // 移除 controlslistconsole.log(`Fixed video ${index + 1}: Added controls, removed controlslist.`);});} catch (error) {console.error('Error fixing video controls:', error);}};// 初始修复fixVideos();// CKEditor 异步加载if (window.CKEDITOR) {CKEDITOR.on('instanceReady', fixVideos);CKEDITOR.on('change', () => setTimeout(fixVideos, 100));}// 动态内容监听const observer = new MutationObserver(fixVideos);observer.observe(document.body, { childList: true, subtree: true });});
</script>
参考文献:
django-ckeditor配置html5video上传视频 - SonnyZhang - 博客园