如何阻止djangocms-text-ckeditor移除HTML标签及属性?
解决djangocms-text-ckeditor 5.1.1自动移除带class的标签问题
问题根源是CKEditor的**自动内容过滤(ACF)**会默认过滤未被允许的标签属性,甚至标签本身。针对你的场景,可通过以下步骤精准配置:
1. 全局配置(settings.py)
在项目settings.py中添加或修改DJANGOCMS_TEXT_CKEDITOR_CONFIG,指定允许标签及class属性:
DJANGOCMS_TEXT_CKEDITOR_CONFIG = { 'toolbar': 'CMS', # 保留django-cms默认工具栏 # 精细控制允许的内容(推荐,避免全局放开带来的安全风险) 'extraAllowedContent': 'i[class];', # 若需要全局允许所有内容(不推荐,仅测试用): # 'allowedContent': True, }
extraAllowedContent:在默认过滤规则基础上追加允许的标签和属性,格式为标签[属性1,属性2];- 若使用
allowedContent: True会完全关闭ACF,可能引入XSS风险,仅建议测试场景使用。
2. 自定义插件局部配置(cms_plugins.py)
如果全局配置未生效,可能是自定义插件的编辑器widget覆盖了全局设置,需在插件代码中单独指定配置:
from django.forms import fields from djangocms_text_ckeditor.widgets import TextEditorWidget from cms.plugin_base import CMSPluginBase from .models import AvilonLayout3Column class AvilonLayout3ColumnPlugin(CMSPluginBase): model = AvilonLayout3Column name = "3列布局" render_template = "plugins/avilon_layout_3column.html" def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) # 为column_1_content字段指定自定义CKEditor配置 form.fields['column_1_content'].widget = TextEditorWidget( config={ 'extraAllowedContent': 'i[class];', 'toolbar': 'CMS', } ) return form
3. 生效配置的必要操作
- 重启Docker容器:确保新配置被加载
- 清除浏览器缓存:避免旧的CKEditor配置残留
- 清除django缓存(若启用):在容器内执行
python manage.py clearcache
4. 验证配置
打开浏览器开发者工具(F12),在控制台输入以下代码验证配置是否加载:
// 替换为你的编辑器ID,可通过查看页面元素获取 CKEDITOR.instances['id_column_1_content'].config.extraAllowedContent
若返回"i[class];"则说明配置已生效。
内容的提问来源于stack exchange,提问作者Mo-ster
相关产品推荐
相关产品推荐

