KindEditor安装配置
WEB开发离不开富文本编辑器,KindEditor和CKEditor是两款不错的第三方插件。
1.kindeditor下载
http://kindeditor.net/down.php
2.目录结构(删除多余的文件)
3.settings.py和urls.py配置
在settings.py 中设置MEDIA_ROOT 目录
#文件上传配置
MEDIA_ROOT = os.path.join(BASE_DIR,’uploads’)
# urls.py 配置
url(r'^admin/uploads/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),
url(r'^uploads/(?P<path>.*)$', views.static.serve, {‘document_root’: settings.MEDIA_ROOT, }),
4.upload.py 文件
该文件存放在根目录同名文件夹下
project---project----upload.py
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
import os
import uuid
import json
import datetime as dt
@csrf_exempt
def upload_image(request, dir_name):
##################
# kindeditor图片上传返回数据格式说明:
# {"error": 1, "message": "出错信息"}
# {"error": 0, "url": "图片地址"}
##################
result = {"error": 1, "message": "上传出错"}
files = request.FILES.get("imgFile", None)
if files:
result =image_upload(files, dir_name)
return HttpResponse(json.dumps(result), content_type="application/json")
#目录创建
def upload_generation_dir(dir_name):
today = dt.datetime.today()
dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
if not os.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)
return dir_name
# 图片上传
def image_upload(files, dir_name):
#允许上传文件类型
allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
file_suffix = files.name.split(".")[-1]
if file_suffix not in allow_suffix:
return {"error": 1, "message": "图片格式不正确"}
relative_path_file = upload_generation_dir(dir_name)
path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
if not os.path.exists(path): #如果目录不存在创建目录
os.makedirs(path)
file_name=str(uuid.uuid1())+"."+file_suffix
path_file=os.path.join(path, file_name)
file_url = settings.MEDIA_URL + relative_path_file + file_name
open(path_file, 'wb').write(files.file.read())
return {"error": 0, "url": file_url}
5.config.js 配置
该配置文件主要是对django admin后台作用的,比如说我们现在有一个news的app,我们需要对该模块下的 news类的content加上富文本编辑器,这里需要做两步
第一:在news 的admin.py中加入
class Media:
js = (
'/static/js/kindeditor-4.1.10/kindeditor-min.js',
'/static/js/kindeditor-4.1.10/lang/zh_CN.js',
'/static/js/kindeditor-4.1.10/config.js',
)
第二:config.js 中配置
上边说了我们是要对news的content加上富文本编辑器,那么我们首先要定位到该文本框的name属性,鼠标右键查看源代码
<textarea class="" cols=60 id=ie_new_content name=new_content rows=10 required>
config.js 中加入:
//news
KindEditor.ready(function(K) {
K.create('textarea[name="new_content"]', {
width : "800px",
height : "500px",
uploadJson: '/admin/uploads/kindeditor',
});
});
这个例子写的太复杂了,直接在页面引用js,然后在javascript标签内初始化富文本就可以。
例子2
普通使用HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<textarea name="content" id="content"></textarea>
<script src="/static/js/jquery-1.12.4.js"></script>
<script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
});
function initKindEditor() {
var kind = KindEditor.create('#content', {
width: '100%', // 文本框宽度(可以百分比或像素)
height: '300px', // 文本框高度(只能像素)
minWidth: 200, // 最小宽度(数字)
minHeight: 400 // 最小高度(数字)
});
}
</script>
</body>
</html>
上传文件示例
kind.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form>
{% csrf_token %}
<div style="width: 500px;margin: 0 auto">
<textarea id="content"></textarea>
</div>
<input type="submit" value="提交"/>
</form>
<script src="/static/js/jquery-1.12.4.js"></script>
<script src="/static/kindeditor-4.1.10/kindeditor-all.js"></script>
<script>
$(function () {
KindEditor.create('#content', {
{# items: ['superscript', 'clearhtml', 'quickformat', 'selectall']#}
{# noDisableItems: ["source", "fullscreen"],#}
{# designMode: false#}
uploadJson: '/upload_img/',
fileManagerJson: '/file_manager/',
allowImageRemote: true,
allowImageUpload: true,
allowFileManager: true,
extraFileUploadParams: {
csrfmiddlewaretoken: "{{ csrf_token }}"
},
filePostName: 'fafafa'
});
})
</script>
</body>
</html>
后台代码
views.py
def kind(request):
return render(request, 'kind.html')
def upload_img(request):
request.GET.get('dir')
print(request.FILES.get('fafafa'))
# 获取文件保存
import json
dic = { #后台向前端返回的值
'error': 0, #0表示的是正确的,1代表错误
'url': '/static/image/图片.jpg',
'message': '错误了...'
}
return HttpResponse(json.dumps(dic))
import os
import time
import json
def file_manager(request):
dic = {}
root_path = 'E:/week_23_1/static'
static_root_path = '/static/'
request_path = request.GET.get('path')
if request_path:
abs_current_dir_path = os.path.join(root_path, request_path)
move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path
else:
abs_current_dir_path = root_path
dic['moveup_dir_path'] = '' # 上一级目录
dic['current_dir_path'] = request_path #current_dir_path 指当前的路径
dic['current_url'] = os.path.join(static_root_path, request_path)
file_list = [] #文件目录
for item in os.listdir(abs_current_dir_path): #listdir 就是把某一路径下的东西全部拿下来
abs_item_path = os.path.join(abs_current_dir_path, item)
a, exts = os.path.splitext(item)
is_dir = os.path.isdir(abs_item_path)
if is_dir:
temp = {
'is_dir': True, #是否是dir
'has_file': True, #目录下面是否存在文件
'filesize': 0, #文件大小是多少
'dir_path': '', #当前的路径是在哪
'is_photo': False, #是否是图片
'filetype': '', #文件的类型是什么
'filename': item, #文件名是什么
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) #文件创始时间是什么
}
else:
temp = {
'is_dir': False,
'has_file': False,
'filesize': os.stat(abs_item_path).st_size,
'dir_path': '',
'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
'filetype': exts.lower().strip('.'),
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
file_list.append(temp)
dic['file_list'] = file_list
return HttpResponse(json.dumps(dic))
一个上传的python例子
效果如下
CKEditor使用配置
目前我用的是CKEditor
1.下载django-ckeditor包
https://pypi.org/project/django-ckeditor/
2.安装插件包,这个是为了和django的model深度融合,不安装只是前端配置使用应该也可以
pip install django-ckeditor
3.settings.py 配置
INSTALLED_APPS = [
'ckeditor', # 富文本编辑器
'ckeditor_uploader',
]
文件最下面加上
CKEDITOR_UPLOAD_PATH = 'ckeditor/'
4.在前端页面创建富文本框
//在页面加入js文件
<script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>
//加入html代码
<textarea type="text" id="id_content" cols="50" name="content" autocomplete="off"></textarea>
//创建CKEDITOR富文本框
function createCkeditor(name) {
var editor = CKEDITOR.instances[name];
if (editor) {
editor.destroy(true); //如果已经有一个实例,先销毁再创建一个。这里name必须传textarea的id。
//CKEDITOR.remove(editor);
}
CKEDITOR.replace(name, {
language: 'zh-cn',
skin: 'moono-lisa',
toolbar: 'Basic',
toolbarCanCollapse: true, //是否可以收缩工具栏
toolbarStartupExpanded: false, //工具栏是否默认展开
allowedContent: true,
removePlugins: 'elementspath',
resize_enabled: false,
width: '800px',
height: '300px',
baseFloatZIndex: '20000000',
});
}
//结合layui的layer弹出层使用,
function openAddSupervise() {
mainIndex = layer.open({
type: 1,
offset: 't',
title: '添加督察督办',
content: $("#saveOrUpdateDiv"),
area: ['1000px', '500px'],
// btn:['保存','放弃'], 因为不能提交激发验证,所以这里不适用btn,而是在content中定义提交表单按钮
/* yes:function(index, layero) {
layer.msg(index);
},
btn2:function(index,layero){
layer.msg(index);
},
*/
success: function (index) {
//清空表单数据
$("#dataFrm")[0].reset(); //dom=>js obj[0],js=>dom $()
url = '{% url "adm:public-supervise-create" %}';
createCkeditor('id_content'); //必须传id 弹出时创建调用上面函数富文本
}
});
5.通过ajax提交富文本内容
## 富文本的本质是用自身替代了html中的textarea,进行了站位,所以直接从textarea取值不行。
等从后台拿到数据,回写的时候,插件会自动把值赋给textarea
var content = CKEDITOR.instances.id_content.getData(); //拿到富文本框实例的内容
document.getElementById("id_content").value = content; //设置到html 表单中的textarea中去,再下一句跟随表单提交
var params = $.param({"department": transferList}, true) + "&" + $.param({"filelist": filelist}, true) + "&" + $("#dataFrm").serialize();
//alert(params);
$.ajax({
type: "POST",
url: url,
data: params,