django使用ckeditor上传图片
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上传图片的更多相关文章
- Ckeditor上传图片返回的JS直接显示出来,未执行!!!
Ckeditor上传图片网上有很多教程. 下面是我今天下午遇到的一个坑...自己挖的坑. 在conotroller里 我开始习惯性的 response.setContentType("app ...
- 去除ckeditor上传图片预览中的英文字母
去除ckeditor上传图片预览中的英文字母 CKEDITOR.replace('text', { filebrowserImageUploadUrl : 'upload_img.do', langu ...
- Django中CKEditor富文本编译器的使用
CKEditor富文本编辑器 1. 安装 pip install django-ckeditor 2. 添加应用 在INSTALLED_APPS中添加 INSTALLED_APPS = [ ... ' ...
- django中ckeditor富文本编辑器使用
1.安装模块 (pillow是python的一个图像处理库) pip install django-ckeditor pip install pillow 2.编辑seetings.py配置文件 IN ...
- 如何去除 ckeditor 上传图片后在原码中留下的 style="width: 100%;height:100px"之类的代码呢?
ckeditor编辑器在上传图片的时候,会神奇的加上一段诡异的代码: 这导致上传的小图也是被拉伸到100%,我根本就没有定义它,找来找去也找不到element.style,原来这是在system.cs ...
- ckeditor上传图片的注意点
1.要在 ckeditor的 config.js 文件中加上 CKEDITOR.editorConfig = function( config ) { config.filebrowserImage ...
- Django添加ckeditor富文本编辑器
源码 https://github.com/django-ckeditor/django-ckeditor 通过pip安装. pip3 install django-ckeditor pip3 ins ...
- 记一次ckeditor上传图片到服务器问题
package com.util;import java.io.IOException; import java.io.PrintWriter; import java.util.List;impor ...
- 使用 CKEditor 上传图片, 粘贴屏幕截图
之前写过wangEditor,那真是好用,文档也清晰,半天就搞定了,无奈没有对应license,只好选择别的. 外语一般,阅读理解都靠蒙.CKEditor官方文档看的我云里雾里,国内的博客比较少,经过 ...
随机推荐
- RAID配置多阵列
感谢: https://www.cnblogs.com/hystj/articles/8672029.html
- Exploit-Exercises nebule 旅行日志(五)
接着上次的路程继续在ubuntu下对漏洞的探索练习,这次是level04了 先看下level04的问题描述: (level4.c) #include <stdlib.h> #include ...
- kali linux 配置嵌入式开发环境
kali linux 2018.2 x64 一.支持i386库 如果你是64位的Kali Linux系统,用如下命令添加i386架构支持到你的开发环境. dpkg --add-architecture ...
- 【SoftwareTesting】Homework2
For the Program1, For Question1: The fault is that in the loop condition, ' i ' should be not less t ...
- Problem 2: Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting w ...
- python命令随记
1. pip版本需要升级命令: python -m pip install --upgrade pip 2.查找Django命令 pip show django 3.查看python安装目录 进入Py ...
- linux安装openssl
1.简介 给网站配置http2发现openssl版本不够,只能靠升级openssl了,shell让安装不再麻烦. 系统环境 centos 7.4 64位 安装 openssl1.1.1a版本 2.查看 ...
- [Java] [Singleton] [DCL][happens-before]
Singleton 只能有一个实例:必须自己创建自己的实例:必须给其他所有对象提供这一实例 实现方法 饿汉式singleton 预先加载法 class Single { private Single( ...
- 2018-2019-2 学号20175223 实验二《Java面向对象程序设计》实验报告
目录 北京电子科技学院(BESTI)实验报告 实验名称:实验二 面向对象程序设计 实验内容.步骤与体会: 一.实验二 面向对象程序设计-1 二.实验二 面向对象程序设计-2 三.实验二 面向对象程序设 ...
- Python第八章(北理国家精品课 嵩天等)
程序设计方法 8.1体育竞技分析实例 from random import random def printIntro(): print("这个程序模拟两个选手A和B的某种竞技比赛" ...