1:下载该文件,解压至相应的js文件目录
http://kindeditor.net/down.php
2:settings.py和urls.py配置
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
需要在url里面配置一下获取路径
from django.conf import settings from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', views.Upload.as_view(), name="upload")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)重点是这一行
3:编写upload.py文件
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}
4: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属性,鼠标右键查看源代码,如下红线标示:
config.js 中加入:
//news KindEditor.ready(function(K) { K.create('textarea[name="new_content"]', { width : "800px", height : "500px", uploadJson: '/admin/uploads/kindeditor', }); });
关于kindeditor(富文本编辑)
POST参数
- imgFile: 文件form名称
- dir: 上传类型,分别为image、flash、media、file
返回格式(JSON)
//成功时 { "error" : 0, "url" : "http://www.example.com/path/to/file.ext" } //失败时 { "error" : 1, "message" : "错误信息" }