这篇文章基于python3.7和Django3.0.6,django-ckeditor的版本为5.9.0.
安装好上面的运行环境后,接下来就是对配置方面详细说明。
1 settings.py 的配置
以下配置均在settings.py文件中完成
(1) INSTALLED_APPS的配置
1 2 3 4 5 6 7 8 9 10 11 | INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor_uploader', 'ckeditor', 'goods', ] |
这里,如果只是使用富文本编辑器,而不涉及上传图片,只需要加入’ckeditor’即可,要用上传图片的功能,就需要加入’ckeditor_uploader’。
(2) 媒体路径的配置
1 2 3 | MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') CKEDITOR_UPLOAD_PATH='images' |
要上传图片,这个配置是必须要有的,
MEDIA_URL 是访问所有媒体文件的路由
MEDIA_ROOT 是媒体文件所在的目录
CKEDITOR_UPLOAD_PATH 是上传文件的目录
配置好后记得在项目根目录下新建一个media目录,再在media文件夹下创建一个images目录,这就是图片上传后所在的目录
2 urls.py的配置
1 2 3 4 5 6 7 8 | from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/',include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) |
这里的配置比较简单,static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
这个是在虚拟环境下必须加入的静态资源的访问配置。
3 models.py中配置模型字段
(1)这里以一个商品类的模型为例,先上代码
1 2 3 4 5 6 7 8 | from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Goods(models.Model): title = models.CharField(max_length=100,verbose_name='标题') photo = models.ImageField(verbose_name='缩略图') l_price = models.IntegerField(verbose_name='价格') content = RichTextUploadingField(verbose_name='详情') |
ckeditor_uploader分为fields和widget,fields用于模型(model),而widget用于表单(form)。
模型基本用于在admin中进行编辑管理,而表单主要用于使前端页面拥有富文本编辑的功能。
模型编辑之后就要执行数据库迁移的操作,控制台输入
(2)后端管理admin.py中的配置
数据迁移完成后需要在admin.py中注册模型
1 2 3 4 5 6 7 | from django.contrib import admin from .models import Goods @admin.register(Goods) class GoodsAdmin(admin.ModelAdmin): list_display = ('title','photo','l_price','content') fields = ('title','photo','l_price','content') |
模型注册后记得在settings.py中加入要管理的app。
到此,后端上传的代码就写好了。运行程序,进入admin管理后台。
这里的编辑器功能我缩减了很多,从而更符合我的需要,具体的配置方法后面会详细说明。
(3) 在前端页面中应用富文本编辑器
很多时候我们需要网站用户在前端页面提交一些带图评论,这时也会需要用到富文本编辑器,使用ckeditor其实也是很容易实现的。
首先,创建一个表单类,新建forms.py文件
1 2 3 4 5 6 7 8 9 10 | from ckeditor_uploader.widg**ets impo**rt CKEditorUploadingWidget from ckeditor.widgets import CKEditorWidget from django import forms from .models import Goods class GoodsAdminForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget,label='详情',required=True) class Meta: model = Goods fields = "__all__" |
注意,这里以Goods为模型,并引入ckeiditor.widget。
接着,在views.py文件中编写返回上面这个表单实例的逻辑
1 2 3 4 5 6 | from django.shortcuts import render from .forms import GoodsAdminForm def edit_goods(request): goods_form = GoodsAdminForm() return render(request,'goods/edit_goods.html',{'goods_form':goods_form}) |
这段代码就是先实例化了一个GoodsAdminForm,然后将这个实例渲染到模板文件edit_goods.html中。
接着看看前端代码的编写。
按照上面代码中
templates目录下创建goods目录,然后创建edit_goods.html文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>编辑商品</title> </head> <body> <div> <form action="." method="post"> {% csrf_token %} 标题:{{ goods_form.title }} 价格:{{ goods_form.l_price }} 详情:{{ goods_form.content }} {{ goods_form.media }} {{ goods_form.body }} <input type="submit" value="提交"> </form> </div> </body> </html> |
最后别忘了路由配置,在urls.py中加入edit_goods的路由
1 2 3 4 5 6 7 8 9 | ... from goods.views import edit_goods ... urlpatterns = [ ... path('edit_goods',edit_goods,name='edit_goods'), ... ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) |
通过浏览器访问127.0.0.1:8000/edit_goods,看一下效果
关于表单提交后保存到数据库的逻辑跟普通表单是一样的,这里不多做赘述。
4 CKEditor 功能界面的配置
CKEditor提供的功能很多,但也有很多功能是我们不需要或者不希望用户使用的。可以通过在
下面是比较完整的配置,可根据自己的需求删除一些不需要的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | CKEDITOR_CONFIGS={ 'default':{ 'skin':'moono', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YouCustomToolbarConfig': [ { 'name': 'basicstyles', 'items': [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] }, { 'name': 'paragraph', 'items': [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] }, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, { 'name': 'insert', 'items': [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] }, '/', { 'name': 'clipboard', 'items': [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] }, {'name': 'editing', 'items': [ 'Find', 'Replace', '-', 'SelectAll']}, { 'name': 'forms', 'items': [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] }, { 'name': 'styles', 'items': [ 'Styles', 'Format', 'Font', 'FontSize' ] }, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, { 'name': 'tools', 'items': [ 'Maximize', 'ShowBlocks', 'Preview', 'Source', ] }, ], 'toolbar': 'YouCustomToolbarConfig', 'height':300, 'width':'auto', 'tabSpaces':4, 'extraPlugins':','.join([ 'div', 'autolink', 'autoembed', 'embedsemantic', 'autogrow', 'image2', # 'devtools', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath', ]), }, } |
这里使用的图片插件是image2,比默认的要精简而且好用。
个人感言
在使用ckeditor时遇到了很多坑,也在网上找了很多资料,问题最多的应该就是运行环境的版本和第三方插件的不兼容,可谓步步艰辛,到这里,算是基本玩明白了ckeditor的使用和配置方法。但还有一些问题找了很多资料也解决不了。希望大家在努力提高自己的路上共勉吧