文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
Django-ckeditor是集成了ckeditor富文本编辑器的django第三方库,可以在admin后台使用。使页面效果更加丰富,同时该富文本编辑器也可以用于form类。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
- 通过pip安装
pip3 install django-ckeditor
pip3 install Pillow
2.在settings.py的INSTALLED_APPS里添加ckeditor和ckeditor_uploader两个应用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
INSTALLED_APPS = (
#
'ckeditor',
'ckeditor_uploader'
)
3.在settings.py里进行ckeditor的相关配置。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmlCKEDITOR_JQUERY_URL = 'https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = 'pillow'
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
'height':600,
'width':800,
},
}
3.在urls.py里配置ckeditor相关的url。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmlfrom 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) # 没有这一句无法显示上传的图片
4.在需要使用富文本编辑器的models.py中修改。其中RichTextField拥有TextField的全部参数,还拥有其他的一些参数。RichTextUploadingField可以上传图片文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmlfrom ckeditor.fields import RichTextField
content = RichTextField()
from ckeditor_uploader.fields import RichTextUploadingField
content = RichTextUploadingField(verbose_name='内容')#可以上传图片
5.在 templates 中使用内容文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html{{ content | safe }}
6.富文本编辑器最终效果文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
7.ckeditor上传文件重命名文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
在和manage.py同级下新建utils.py文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmldef get_filename(filename, request):
return filename.upper()
在settings.py添加配置文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmlCKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
8.调整ckeditor主题颜色。在/static/ckeditor/下创建在custom.css
,添加以下CSS代码以更改编辑器的主题颜色:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html/* Set the background color */
.cke_editable {
background-color: #f8f8f8;
}
/* Set the font color */
.cke_editable p {
color: #333;
}
在这个例子中,我们将背景颜色设置为淡灰色(#f8f8f8
),将字体颜色设置为黑色(#333
)。您可以根据自己的需要调整这些值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.html
在Django的settings.py
文件中,将CKEDITOR_CONFIGS
的contentsCss
属性设置为刚刚创建的CSS文件的路径。例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/48141.htmlpythonCKEDITOR_CONFIGS = {
'default': {
'contentsCss': '/static/ckeditor/custom.css',
'toolbar': 'full',
'height': 300,
},
}