Django添加ckeditor富文本编辑器教程

Django-ckeditor是集成了ckeditor富文本编辑器的django第三方库,可以在admin后台使用。使页面效果更加丰富,同时该富文本编辑器也可以用于form类。
- 通过pip安装
pip3 install django-ckeditorpip3 install Pillow
2.在settings.py的INSTALLED_APPS里添加ckeditor和ckeditor_uploader两个应用。
INSTALLED_APPS = (#'ckeditor','ckeditor_uploader')
3.在settings.py里进行ckeditor的相关配置。
CKEDITOR_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。
from django.conf import settingsfrom django.conf.urls.static import staticfrom django.conf.urls import url,includeurlpatterns = [url(r'^ckeditor/', include('ckeditor_uploader.urls')),] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # 没有这一句无法显示上传的图片
4.在需要使用富文本编辑器的models.py中修改。其中RichTextField拥有TextField的全部参数,还拥有其他的一些参数。RichTextUploadingField可以上传图片
from ckeditor.fields import RichTextFieldcontent = RichTextField()from ckeditor_uploader.fields import RichTextUploadingFieldcontent = RichTextUploadingField(verbose_name='内容')#可以上传图片
5.在 templates 中使用内容
{{ content | safe }}
6.富文本编辑器最终效果

7.ckeditor上传文件重命名
在和manage.py同级下新建utils.py
def get_filename(filename, request):return filename.upper()
在settings.py添加配置
CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
8.调整ckeditor主题颜色。在/static/ckeditor/下创建在custom.css,添加以下CSS代码以更改编辑器的主题颜色:
/* Set the background color */.cke_editable {background-color: #f8f8f8;}/* Set the font color */.cke_editable p {color: #333;}
在这个例子中,我们将背景颜色设置为淡灰色(#f8f8f8),将字体颜色设置为黑色(#333)。您可以根据自己的需要调整这些值。
在Django的settings.py文件中,将CKEDITOR_CONFIGS的contentsCss属性设置为刚刚创建的CSS文件的路径。例如:
pythonCKEDITOR_CONFIGS = {'default': {'contentsCss': '/static/ckeditor/custom.css','toolbar': 'full','height': 300,},}
THE END




