CKEditor
富文本即具备丰富样式格式的文本。在运营后台,运营人员需要录入课程的相关描述,可以是包含了HTML语法格式的字符串。为了快速简单的让用户能够在页面中编辑带格式的文本,我们引入富文本编辑器。
富文本编辑器
- 安装
pip install django-ckeditor - 添加应用
在INSTALLED_APPS中添加
INSTALLED_APPS = [
…
‘ckeditor’, # 富文本编辑器
‘ckeditor_uploader’, # 富文本编辑器上传图片模块
…
]
3. 添加CKEditor设置
在settings/dev.py中添加
富文本编辑器ckeditor配置
CKEDITOR_CONFIGS = {
‘default’: {
‘toolbar’: ‘full’, # 工具条功能
‘height’: 300, # 编辑器高度
# ‘width’: 300, # 编辑器宽
},
}
CKEDITOR_UPLOAD_PATH = ‘’ # 上传图片保存路径,使用了FastDFS,所以此处设为’’
4. 添加ckeditor路由
在总路由中添加
接下来在urls.py里配置ckeditor相关的url。
# 1.
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
# 2.
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url,include
urlpatterns = [
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # 没有这一句无法显示上传的图片
- 为模型类添加字段
ckeditor提供了两种类型的Django模型类字段
ckeditor.fields.RichTextField 不支持上传文件的富文本字段
ckeditor_uploader.fields.RichTextUploadingField 支持上传文件的富文本字段
在商品模型类(SPU)中,要保存商品的详细介绍、包装信息、售后服务,这三个字段需要作为富文本字段
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class Goods(BaseModel):
“”"
商品SPU
“”"
…
desc_detail = RichTextUploadingField(default=’’, verbose_name=‘详细介绍’)
desc_pack = RichTextField(default=’’, verbose_name=‘包装信息’)
desc_service = RichTextUploadingField(default=’’, verbose_name=‘售后服务’)
######在应用中改写路由和类视图,使用permission_classes对请求权限进行限制
# 配置路由
urlpatterns = [
url(r'^upload/$', ImageUploadView.as_view()),
]
from ckeditor_uploader import image_processing,utils
from django.conf import settings
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.utils.html import escape
class ImageUploadView(APIView):
permission_classes = [IsAuthenticated]
http_method_names = ['post']
def post(self, request, **kwargs):
"""
Uploads a file and send back its URL to CKEditor.
"""
uploaded_file = request.FILES['upload']
backend = image_processing.get_backend()
ck_func_num = request.GET.get('CKEditorFuncNum')
if ck_func_num:
ck_func_num = escape(ck_func_num)
# Throws an error when an non-image file are uploaded.
if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
try:
backend.image_verify(uploaded_file)
except utils.NotAnImageException:
return HttpResponse("""
<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
</script>""".format(ck_func_num))
saved_path = self._save_file(request, uploaded_file)
if len(str(saved_path).split('.')) > 1:
if(str(saved_path).split('.')[1].lower() != 'gif'):
self._create_thumbnail_if_needed(backend, saved_path)
url = utils.get_media_url(saved_path)
if ck_func_num:
# Respond with Javascript sending ckeditor upload url.
return HttpResponse("""
<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
</script>""".format(ck_func_num, url))
else:
retdata = {'url': url, 'uploaded': '1',
'fileName': uploaded_file.name}
return JsonResponse(retdata)
- 修改Bug
通过Django上传的图片保存到了FastDFS中,而保存在FastDFS中的文件名没有后缀名,ckeditor在处理上传后的文件名按照有后缀名来处理,所以会出现bug错误,
修正方法
找到虚拟环境目录中的ckeditor_uploader/views.py文件,如
~/.virtualenvs/meiduo/lib/python3.5/site-packages/ckeditor_uploader/views.py
将第95行代码修改如下:
扩展:
CKEditor富文本编辑器在Python中的应用,不光只有后端通过admin后端来实现,还可以通过前端来实现具体代码如下:
tinymce.init({
//选择class为content的标签作为编辑器
selector: '#rich_content',
//方向从左到右
directionality:'ltr',
//语言选择中文
language:'zh_CN',
//高度为400
height:300,
width:570,
//工具栏上面的补丁按钮
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality template paste textcolor',
'codesample imageupload',
],
//工具栏的补丁按钮
toolbar: 'insertfile undo redo | \
styleselect | \
bold italic | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | \
link image | \
print preview media fullpage | \
forecolor backcolor emoticons |\
codesample fontsizeselect fullscreen |\
imageupload',
//字体大小
fontsize_formats: '10pt 12pt 14pt 18pt 24pt 36pt',
//按tab不换行
nonbreaking_force_tab: true,
imageupload_url: "/user/submit-image"
});