效果图:
1.安装django-ckeditor
pip install django-ckeditor
如果需要上传图片或者文件,还需要安装pillow
pip install pillow
2.配置模型字段
如果编辑器需要上传图片或者文件,需要引入RichTextUploadingField
,否则只需要引入RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class Activity(models.Model):
desc = RichTextUploadingField(verbose_name="活动描述")
3.settings中配置
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full', #工具栏全部功能
'height': 300, # 高度
'width': 730, # 宽度
},
}
CKEDITOR_UPLOAD_PATH = 'ckeditor/' #上传文件的目录
CKEDITOR_IMAGE_BACKEND = 'pillow' #pillow做为backend
4.form表单配置
这里只需要使用modelForm,不需要配置
from django import forms
from learntime.activity.models import Activity
class ActivityForm(forms.ModelForm):
class Meta:
fields = "__all__" #引入全部字段
model = Activity
5.urls配置
以下是admin中配置的urls,如果在自己的项目中就不能这样写
urlpatterns = [
...
path('ckeditor/', include('ckeditor_uploader.ckeditor_urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
网上其他教程都是在admin中配置ckeditor,如果按照如上代码可能会发现图片上传失败,点进源码可以看到,图片上传的成功条件为:django的用户表is_staff为True
,自己的项目中可能并没有这样设定。
urls源码如下:
from __future__ import absolute_import
from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from . import views
urlpatterns = [
url(r'^upload/', staff_member_required(views.upload), name='ckeditor_upload'),
url(r'^browse/', never_cache(staff_member_required(views.browse)), name='ckeditor_browse'),
]
staff_member_required为装饰器,我们可以把它替换为login_required
,即必须登录之后才能上传图片。
修改后的代码如下:
xxx.utils.ckeditor_urls.py
from __future__ import absolute_import
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import never_cache
from ckeditor_uploader import views
urlpatterns = [
url(r'^upload/', login_required(views.upload), name='ckeditor_upload'),
url(r'^browse/', never_cache(login_required(views.browse)), name='ckeditor_browse'),
]
urls.py
path('ckeditor/', include('xxx.utils.ckeditor_urls')),
按照如上配置就能完美上传图片和文件了。