Django接入富文本编辑ckeditor
后台配置ckeditor
- 安装ckeditor
pip install django-ckeditor
- 配置ckeditor
2.1 不包含图片上传功能
2.1.1 在settings.py中的INSTALLED_APPS添加ckeditor,并配置ckeditor指定数量工具栏
INSTALLED_APPS添加ckeditor
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogger',
'comment',
'post',
'ckeditor', # 添加该行
# 'ckeditor_uploader',
]
配置ckeditor工具栏
CKEDITOR_CONFIGS = {
# django-ckeditor默认使用default配置
'default': {
# 编辑器宽度自适应
'width':'auto',
'height':'250px',
# tab键转换空格数
'tabSpaces': 4,
# 工具栏风格
'toolbar': 'Custom', # 指定数量工具栏
# 'toolbar':'full', # 完整工具条
# 自定义工具栏
# 工具栏按钮
'toolbar_Custom': [
# 表情 代码块
['Smiley', 'CodeSnippet'],
# 字体风格
['Bold', 'Italic', 'Underline', 'RemoveFormat', 'Blockquote'],
# 字体颜色
['TextColor', 'BGColor'],
# 链接
['Link', 'Unlink'],
# 列表
['NumberedList', 'BulletedList'],
# 图片
['Image', 'Link', 'Unlink'],
# 最大化
['Maximize']
],
# 加入代码块插件
'extraPlugins': ','.join(['codesnippet','widget','lineutils',]),
}
}
2.1.2 model.py文件中将TextField字段替换为RichTextField字段
from django.db import models
from ckeditor.fields import RichTextField
# Create your models here.
class Blogger(models.Model):
name = models.CharField('博主名',default='狼性书生',max_length=20)
head_photo = models.ImageField('头像', upload_to='blog_img',null=True,blank=True,default='/cover_img/default.jpg')
blog_major = models.CharField('职业',default='程序猿',max_length=20)
autograph = RichTextField('个性签名',default='个性签名') #将TextField字段替换为RichTextField字段
blog_email = models.EmailField('博主邮箱',default='794859685@qq.com')
def __str__(self):
return self.name
class Link(models.Model):
link_name = models.CharField("链接",max_length=50)
blogger = models.ForeignKey('Blogger',on_delete=models.CASCADE,related_name='blogger_link')
def __str__(self):
return self.link_name
2.1.3 将model模型注册到后台,运行测试
from django.contrib import admin
from .models import Blogger,Link,Layout
from django.utils.safestring import mark_safe
# Register your models here.
admin.site.site_title="Mr Wolf Blog"
admin.site.site_header="Mr Wolf博客管理系统"
@admin.register(Blogger)
class BloggerAdmin(admin.ModelAdmin):
list_display = ['id','name','image_data','blog_major','autograph','blog_email']
list_editable = ['name','blog_major','blog_email']
# 缩略图,后台展示页显示缩略图
def image_data(self,obj):
return mark_safe(u'<img src="%s" width="100px" />' % obj.head_photo.url)
image_data.short_description = u'头像'
@admin.register(Link)
class LinkAdmin(admin.ModelAdmin):
list_display = ['id','link_name','blogger']
list_editable = ['link_name','blogger']
2.2 包含图片上传功能
2.2.1 在settings.py中INSTALLED_APPS添加ckeditor和ckeditor_uploader,并配置ckeditor工具栏和图片上传路径
添加ckeditor和ckeditor_uploader
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogger',
'comment',
'post',
'ckeditor', # 添加该行
'ckeditor_uploader', # 添加该行
]
配置ckeditor工具栏
CKEDITOR_CONFIGS = {
# django-ckeditor默认使用default配置
'default': {
# 编辑器宽度自适应
'width':'auto',
'height':'250px',
# tab键转换空格数
'tabSpaces': 4,
# 工具栏风格
'toolbar': 'Custom',
# 'toolbar':'full', # 完整工具条
# 自定义工具栏
# 工具栏按钮
# 'toolbar_Custom': [
# # 表情 代码块
# ['Smiley', 'CodeSnippet'],
# # 字体风格
# ['Bold', 'Italic', 'Underline', 'RemoveFormat', 'Blockquote'],
# # 字体颜色
# ['TextColor', 'BGColor'],
# # 链接
# ['Link', 'Unlink'],
# # 列表
# ['NumberedList', 'BulletedList'],
# # 图片
# ['Image', 'Link', 'Unlink'],
# # 最大化
# ['Maximize']
# ],
# # 加入代码块插件
'extraPlugins': ','.join(['codesnippet','prism','uploadimage','widget','lineutils',]),
}
}
配置图片上传路径
MEDIA_URL = '/media/' # # 用于指定url路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') # 用于指定上传文件的存储路径
CKEDITOR_UPLOAD_PATH = 'upload/' # 图片将上传到项目下的media/upload路径下,图片的url是 /media/upload/
CKEDITOR_IMAGE_BACKEND = 'pillow' # 用于生成图片缩略图,在编辑器里浏览上传的图片
2.2.2 配置根urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include('ckeditor_uploader.urls')), #配置该行
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #配置该行
2.2.3 将TextField字段替换为RichTextUploadingField字段
import os
import time
import datetime
from django.db import models
# from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
# Create your models here.
def modify_path(instance, filename):
'''
重定义封面保存路径
:param instance: self
:param filename: 文件名
:return: 新路径
'''
ext = filename.split('.').pop()
now_date = datetime.datetime.now().strftime('%Y%m%d')
now_time = int(time.time())
filename = '{0}{1}.{2}'.format(now_date, now_time, ext)
return os.path.join('cover_img', now_date, filename)
class Post(models.Model):
'''
文章模型
'''
title = models.CharField('标题',max_length=100,default='无标题名',null=True,blank=True)
cover = models.ImageField('封面', upload_to=modify_path,null=True,blank=True,default='/cover_img/default.jpg')
create_time = models.DateTimeField('创建时间',auto_now=True)
content = RichTextUploadingField('文章内容',default='文章内容') # 将TextField字段替换为RichTextUploadingField字段
is_publish = models.BooleanField(default=False)
is_comment = models.BooleanField(default=False)
category = models.ForeignKey('Category',on_delete=models.CASCADE,related_name='post')
def __str__(self):
return self.title
# 完善后台数据显示过长情况
def short_detail(self):
if len(str(self.content)) > 30:
return '{}...'.format(str(self.content)[0:29])
else:
return str(self.content)
short_detail.allow_tags = True
short_detail.short_description = u'文章内容'
class Category(models.Model):
post_category = models.CharField('文章类别',max_length=20,default='杂记')
def __str__(self):
return self.post_category
将model模型注册到后台,运行测试
from django.contrib import admin
from .models import Post,Category
from django.utils.safestring import mark_safe
# Register your models here.
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['id','title','image_data','create_time','short_detail','is_publish','is_comment','category']
list_editable = ['is_publish','is_comment','category']
list_filter = ['title','create_time','is_publish','is_comment','category']
# readonly_fields = ('image_data',) # 必须加这行 否则访问编辑页面会报错
# 缩略图显示
def image_data(self,obj):
return mark_safe(u'<img src="%s" width="100px" />' % obj.cover.url)
image_data.short_description = u'封面'
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['id','post_category']
list_editable = ['post_category']
- 迁移后运行
富文本图片自适应(兼容手机端):在高级选项中配置:-ms-interpolation-mode:bicubic; float:left; width:100%
效果图
代码高亮参考以下文章