1、在模型类中设置字段为富文本类型,这里需要注意引入的是RichTextUploadingField,以允许上传图片,需要和RichTextField区分开
from ckeditor_uploader.fields import RichTextUploadingField
class spit_model(models.Model):
"""模型类"""
user = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='吐槽发布者')
content = RichTextUploadingField(verbose_name='吐槽内容', max_length=200)
2、项目中ckeditor的安装及配置
pip install django-ckeditor
INSTALLED_APPS = [
...
'ckeditor', # 富文本编辑器
'ckeditor_uploader', # 富文本编辑器上传图片模块
...
]
# 富文本编辑器ckeditor配置
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full', # 工具条功能
'height': 300, # 编辑器高度
'width': 300, # 编辑器宽
},
}
CKEDITOR_UPLOAD_PATH = '' # 图片ckeditor文件上传路径,这里使用七牛云存储,不填
2、html页面中加入textarea标签
<div>
<textarea id="editor_id"></textarea>
</div>
3、页面中引入控制html页面的JS和ckeditor的JS文件, 在django的installed_app中注册应用时,会自动在虚拟环境中生成应用信息/home/python/.virtualenvs/django_1.11.16_py3/lib/python3.5/site-packages/ckeditor/static/ckeditor/ckeditor/
在js路径前加上域名,否则服务器会在live-server的默认端口下进行网络通讯,查找js
<script type="text/javascript" src="js/spit-submit.js"></script>
<script src="http://127.0.0.1:8000/static/ckeditor/ckeditor/ckeditor.js"></script>
4、在vue变量的mounted方法中加入
let vm = new Vue({
...
mounted:function () {
CKEDITOR.replace('editor_id', { filebrowserUploadUrl:'http://127.0.0.1:8000/ckeditor/upload/' }); // 将id选择器的文本域替换成为富文本,并手动设置文件上传的请求路径,默认请求路径为live-server的路径,必须设置为服务器的域名和端口
},
});
5、后端设置总路由,'ckeditor_uploader.urls'中会将接收到的请求进行csrf校验免除,并限制了只有登录用户才可以上传图片,ckeditor默认应用的是django-admin的用户校验方法,django-admin的校验方法不允许跨域请求,我们需要使上传图片的类试图函数继承自django-restframework的APIVIew,
# url(r'^ckeditor/', include('ckeditor_uploader.urls')), # 为富文本编辑器添加总路由
# url(r'^ckeditor/upload/', ImageUploadView.as_view()), # 为富文本编辑器添加总路由
# url(r'^ckeditor/upload/', csrf_exempt(ImageUploadView.as_view())), # 为富文本编辑器添加总路由
url(r'^ckeditor/', csrf_exempt(ImageUploadView.as_view())), # 为富文本编辑器添加总路由
6、在应用中改写路由和类视图,使用permission_classes对请求权限进行限制
# 配置路由
urlpatterns = [
url(r'^upload/$', ImageUploadView.as_view()),
]
from ckeditor_uploader import image_processing,utils
from django.conf import settings
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.utils.html import escape
class ImageUploadView(APIView):
permission_classes = [IsAuthenticated]
http_method_names = ['post']
def post(self, request, **kwargs):
"""
Uploads a file and send back its URL to CKEditor.
"""
uploaded_file = request.FILES['upload']
backend = image_processing.get_backend()
ck_func_num = request.GET.get('CKEditorFuncNum')
if ck_func_num:
ck_func_num = escape(ck_func_num)
# Throws an error when an non-image file are uploaded.
if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
try:
backend.image_verify(uploaded_file)
except utils.NotAnImageException:
return HttpResponse("""
<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
</script>""".format(ck_func_num))
saved_path = self._save_file(request, uploaded_file)
if len(str(saved_path).split('.')) > 1:
if(str(saved_path).split('.')[1].lower() != 'gif'):
self._create_thumbnail_if_needed(backend, saved_path)
url = utils.get_media_url(saved_path)
if ck_func_num:
# Respond with Javascript sending ckeditor upload url.
return HttpResponse("""
<script type='text/javascript'>
window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
</script>""".format(ck_func_num, url))
else:
retdata = {'url': url, 'uploaded': '1',
'fileName': uploaded_file.name}
return JsonResponse(retdata)