python online json editor_python+django常用富文本插件使用配置(ckeditor,kindeditor)
KindEditor安装配置
WEB开发离不开富文本编辑器,KindEditor和CKEditor是两款不错的第三方插件。
1.kindeditor下载
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[^/]+)$', upload_image, name='upload_image'),
url(r'^uploads/(?P.*)$', views.static.serve, {‘document_root’: settings.MEDIA_ROOT, }),
4.upload.py 文件
该文件存放在根目录同名文件夹下
project---project----upload.py
#-*- coding: utf-8 -*-
from django.http importHttpResponsefrom django.conf importsettingsfrom django.views.decorators.csrf importcsrf_exemptimportosimportuuidimportjsonimportdatetime as dt
@csrf_exemptdefupload_image(request, dir_name):##################
#kindeditor图片上传返回数据格式说明:
#{"error": 1, "message": "出错信息"}
#{"error": 0, "url": "图片地址"}
##################
result = {"error": 1, "message": "上传出错"}
files= request.FILES.get("imgFile", None)iffiles:
result=image_upload(files, dir_name)return HttpResponse(json.dumps(result), content_type="application/json")#目录创建
defupload_generation_dir(dir_name):
today=dt.datetime.today()
dir_name= dir_name + '/%d/%d/' %(today.year,today.month)if notos.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)returndir_name#图片上传
defimage_upload(files, dir_name):#允许上传文件类型
allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
file_suffix= files.name.split(".")[-1]if file_suffix not inallow_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中加入
classMedia:
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属性,鼠标右键查看源代码
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
initKindEditor();
});
function initKindEditor() {
var kind= KindEditor.create('#content', {
width:'100%', //文本框宽度(可以百分比或像素)
height:'300px', //文本框高度(只能像素)
minWidth:200, //最小宽度(数字)
minHeight:400 //最小高度(数字)
});
}
上传文件示例
kind.html
{% csrf_token %}
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'});
})
后台代码
views.pydefkind(request):return render(request, 'kind.html')defupload_img(request):
request.GET.get('dir')print(request.FILES.get('fafafa'))#获取文件保存
importjson
dic= { #后台向前端返回的值
'error': 0, #0表示的是正确的,1代表错误
'url': '/static/image/图片.jpg','message': '错误了...'}returnHttpResponse(json.dumps(dic))importosimporttimeimportjsondeffile_manager(request):
dic={}
root_path= 'E:/week_23_1/static'static_root_path= '/static/'request_path= request.GET.get('path')ifrequest_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 elsemove_up_dir_pathelse:
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)ifis_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'] elseFalse,'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_listreturn HttpResponse(json.dumps(dic))
一个上传的python例子
效果如下
CKEditor使用配置
目前我用的是CKEditor
1.下载django-ckeditor包
2.安装插件包,这个是为了和django的model深度融合,不安装只是前端配置使用应该也可以
pip install django-ckeditor
3.settings.py 配置
INSTALLED_APPS = [
'ckeditor', # 富文本编辑器
'ckeditor_uploader',
]
文件最下面加上
CKEDITOR_UPLOAD_PATH = 'ckeditor/'
4.在前端页面创建富文本框
//在页面加入js文件
//加入html代码
//创建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,
python online json editor_python+django常用富文本插件使用配置(ckeditor,kindeditor)相关推荐
- vue使用富文本插件vue elemnt-tiptap和vue-quill-editor
这两天由于项目要实现新闻发布的功能,所以上github和gitee找了一些项目,发现都是用富文本插件编译成html来实现功能.经过尝试和寻找,我使用了vue elemnt-tiptap和vue-qui ...
- [xPlugins] 开发中常用富文本编辑器介绍
富文本编辑器学习,常见富文本编辑器有: CKeditor(FCkeditor).UEditor(百度推出的).NicEdit.KindEditor CKEditor 即 FCKEditor FCKed ...
- vue2 使用富文本插件 vue-tinymce(tinymce)
富文本组件: vue-tinymce 配置教程 1.package.json 添加依赖及对应版本 dependencies 依赖管理下添加 "tinymce": "^5. ...
- 微信小程序中使用富文本插件 wxParse
github下载地址:https://github.com/icindy/wxParse. 下载完成后,复制 wxParse 文件夹到项目目录中(例如: utils 目录下). 在需要使用的 JS 文 ...
- Django实现的博客系统中使用富文本编辑器ckeditor
操作系统为OS X 10.9.2,Django为1.6.5. 1.下载和安装 1.1 安装 ckeditor 下载地址 https://github.com/shaunsephton/django-c ...
- 使用Django和Python创建Json response
版权声明:本文为博主原创文章.欢迎转载. https://blog.csdn.net/fengyu09/article/details/30785101 使用jquery的.post提交,并期望得到多 ...
- Django 3.2.5博客开发教程:使用富文本编辑器添加数据
在Django admin后台添加数据的时候,文章内容文本框想发布一篇图文并茂的文章需就得手写Html代码,这十分吃力,也没法上传图片和文件.这显然不是我等高大上程序猿想要的. 为提升效率,我们可以使 ...
- python 创建json_使用Django和Python创建Json response的方法
使用jQuery的.post提交,并期望得到多个数据,Python后台要使用json格式. 不指定datatype为json,让jquery自行判断数据类型.(注:跨域名请求数据,则使用 jsonp字 ...
- Django中使用富文本编辑器Uedit
Uedit是百度一款非常好用的富文本编辑器 一.安装及基本配置 官方GitHub(有详细的安装使用教程):https://github.com/zhangfisher/DjangoUeditor 1. ...
- Python项目中用富文本编辑器展示精美网页
富文本编辑器实现效果图: 左侧编辑区域,右侧渲染到HTML显示效果,除了渲染时候代码样式有所不同,其他标题.文字.图片基本满足所见即所得的效果 下面讲解富文本编辑器在Django项目中如何使用 1.前 ...
最新文章
- 《统一沟通-微软-实战》-5-部署-SharePoint Server 2010
- DWS和各异构数据库的差异对比
- python urllib.request 爬虫 数据处理-Python网络爬虫(基于urllib库的get请求页面)
- painticon java_新人,关于java的 paintIcon()方法
- Shell终端快捷键总结(mac)
- linux 拨号网关,用LINUX做在一张软盘上的拨号网关 (转)
- 如何对RTSP播放器做功能和性能评估
- webstorm目录定位(自动定位)当前编辑的文件 - 设置篇
- .net下导致Session失效的一种情况:js教本中使用window.open和window.showModalDialog时需要注意...
- python中类的构成_Python中类型关系和继承关系实例详解
- matlab 中文件夹下图像的批处理
- Analytical.Graphics.STK.Pro.v8.11
- Win7 64位操作系统连接HP 1010打印机完美解决方案
- 算法基础:基本数据结构的特点:队列 vs 栈
- c语言什么意思000094,Hello World 背后的真实故事
- 个人微信支付接口在哪申请
- 实例教学!12种透明背景的万能设计方法
- MDS(多维尺度变换)降维算法
- 表格自适应 css,css 表格自适应一些方法总结
- 时间获取相关函数mktime()、gmtime()