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': '',
'fileName': uploaded_file.name}
return JsonResponse(retdata)

django使用ckeditor上传图片的更多相关文章

  1. Ckeditor上传图片返回的JS直接显示出来,未执行!!!

    Ckeditor上传图片网上有很多教程. 下面是我今天下午遇到的一个坑...自己挖的坑. 在conotroller里 我开始习惯性的 response.setContentType("app ...

  2. 去除ckeditor上传图片预览中的英文字母

    去除ckeditor上传图片预览中的英文字母 CKEDITOR.replace('text', { filebrowserImageUploadUrl : 'upload_img.do', langu ...

  3. Django中CKEditor富文本编译器的使用

    CKEditor富文本编辑器 1. 安装 pip install django-ckeditor 2. 添加应用 在INSTALLED_APPS中添加 INSTALLED_APPS = [ ... ' ...

  4. django中ckeditor富文本编辑器使用

    1.安装模块 (pillow是python的一个图像处理库) pip install django-ckeditor pip install pillow 2.编辑seetings.py配置文件 IN ...

  5. 如何去除 ckeditor 上传图片后在原码中留下的 style="width: 100%;height:100px"之类的代码呢?

    ckeditor编辑器在上传图片的时候,会神奇的加上一段诡异的代码: 这导致上传的小图也是被拉伸到100%,我根本就没有定义它,找来找去也找不到element.style,原来这是在system.cs ...

  6. ckeditor上传图片的注意点

    1.要在 ckeditor的  config.js 文件中加上 CKEDITOR.editorConfig = function( config ) { config.filebrowserImage ...

  7. Django添加ckeditor富文本编辑器

    源码 https://github.com/django-ckeditor/django-ckeditor 通过pip安装. pip3 install django-ckeditor pip3 ins ...

  8. 记一次ckeditor上传图片到服务器问题

    package com.util;import java.io.IOException; import java.io.PrintWriter; import java.util.List;impor ...

  9. 使用 CKEditor 上传图片, 粘贴屏幕截图

    之前写过wangEditor,那真是好用,文档也清晰,半天就搞定了,无奈没有对应license,只好选择别的. 外语一般,阅读理解都靠蒙.CKEditor官方文档看的我云里雾里,国内的博客比较少,经过 ...

随机推荐

  1. jquery.validate.js使用实例

    一.常用方式: $('form').validate({  rules: {},        messages: { },        submitHandler: function () {}) ...

  2. 基于.NET平台常用的框架整理<转载>

    转载来自:http://www.cnblogs.com/hgmyz/p/5313983.html 基于.NET平台常用的框架整理   自从学习.NET以来,优雅的编程风格,极度简单的可扩展性,足够强大 ...

  3. shell练习题3

    需求如下: 请按照这样的日期格式(xxxx-xx-xx)每天生成一个文件,例如今天生成的文件为2018-10-19.log, 并把磁盘的使用情况入到这个文件,(不需要写cron,写脚本即可) 参考解答 ...

  4. Intellij IDEA xxx.properties变成纯文本模式解决方案

    今天在创建xxx.properties的时候不知道按到了哪里,结果让它编程了纯文本模式,重命名这个文件或者删掉,重新创建这个同名文件,换一个项目,始终是文本文件类型,就估计不是项目问题,是intell ...

  5. Web开发常见的几个漏洞解决方法 (转)

    基本上,参加的安全测试(渗透测试)的网站,可能或多或少存在下面几个漏洞:SQL注入漏洞.跨站脚本攻击漏洞.登陆后台管理页面.IIS短文件/文件夹漏洞.系统敏感信息泄露. 1.测试的步骤及内容 这些安全 ...

  6. 读取HeidiSQL 配置文件中的密码

    读取HeidiSQL 配置文件中的密码 2017-1-21 5:42:01 codegay HeidiSQL是一款开源的SQL管理工具,用管理MYSQL,MSSQL 等数据库, 很多管理工具都会把密码 ...

  7. [python] [Jupyter Notebook]

    最近又要用notebook  转一篇我原来写的安装教程 还是很好用的. IPython是一个 Python 的一个交互式 shell,它提供了很多内建的函数.Jupyter Notebook是IPyt ...

  8. c++ 集合的增删改查,与两集合的合并 缺陷(空间大小不灵活)

    #if 1 #include <iostream> #include <stdlib.h> using namespace std; class List { public: ...

  9. 我的自定义框架 || 基于Spring Boot || 第一步

    今天在园子里面看到一位大神写的springboot做的框架,感觉挺不错,遂想起来自己还没有一个属于自己的框架,决定先将大神做好的拿过来,然后加入自己觉得需要的模块,不断完善 目前直接复制粘贴过来的,后 ...

  10. select中想要加a链接 并且新窗口打开

    //新窗口打开 <select id="" onchange="window.open(this.value)"> <option value ...