首先自定义widget,继承Input
from django.forms.widgets import Input
class TyEditorInput(Input):
template_name = '../templates/widgets/editor.html'
自定义wangeditor模板
<div class="editor" id="editor">
{% autoescape off%}
{% if widget.value != None %} {{ widget.value|stringformat:'s' }} {% endif %}
{% endautoescape %}
</div>
<input class="content" id="content" name="{{ widget.name }}" {% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %} style="display: none;" />
{% load static %}
<script src="{% static 'plugins/wangeditor/wangEditor.min.js' %}"></script>
<script type="text/javascript">
var E = window.wangEditor
var editor = new E('#editor')
var text = document.getElementById("content")
editor.customConfig.uploadImgServer = '/backend/upload'
editor.customConfig.uploadImgParams = {
updir: 'detail',
csrfmiddlewaretoken: $.cookie('csrftoken')
}
editor.customConfig.uploadFileName = 'image'
editor.customConfig.onchange = function (html) {
document.getElementById("content").value = html
}
editor.create()
text.value = editor.txt.html()
</script>
后台上传图片并返回
import json, time, uuid, os.path
from django.http import HttpResponse
from django.views.generic.base import View
from common.models.Attachment import Attachment
class UploadFileView(View):
def post(self, request, *args, **kwargs):
resp = {'errno': 100, 'data': '请选择图片'}
#upfile = request.FILES.get('image', None)
upfiles = request.FILES.getlist('image', None)
updir = request.POST.get('updir', 'common')
if(upfiles == None):
return HttpResponse(json.dumps(resp), content_type="application/json")
resUrls = []
resIds = []
for up in upfiles:
upfileres = self._upload(up, updir)
resUrls.append(upfileres['url'])
resIds.append(upfileres['id'])
#前端使用的plopload上传,一次上传一张,多张分多次上传, 使用的wangeditor,是多张图片是一次上传的
if updir == 'detail':
resp = {'errno': 0, 'data': resUrls}
else:
resp = {'errno': 200, 'id': resIds[0], 'url': resUrls[0]}
return HttpResponse(json.dumps(resp), content_type="application/json")
def _upload(self, upfile, updir):
new_file_name = self._hash_filename(upfile.name)
res_save_path = self._get_path(updir)
save_path = res_save_path['save_path']
local_save_path = res_save_path['local_save_path']
local_save_file = local_save_path + new_file_name
save_file = save_path + new_file_name
url = 'http://127.0.0.1:8000/' + save_file
with open(local_save_file, 'wb') as f:
for line in upfile.chunks():
f.write(line)
f.close()
model = Attachment()
model.original_name = upfile.name
model.name = new_file_name
model.url = save_file
model.status = 0
model.save()
return {'id': model.id, 'url': url}
def _hash_filename(self, filename):
_, suffix = os.path.splitext(filename)
return '%s%s' % (uuid.uuid4().hex, suffix)
def _get_path(self, updir):
if(updir == ''):
path = 'static/images/' + time.strftime("%Y%m%d", time.localtime()) + '/'
else:
path = 'static/images/' + updir + '/' + time.strftime("%Y%m%d", time.localtime()) + '/'
# 本地储存路径
local_save_path = os.path.join('frontend', path)
# 数据库存储路径
save_path = os.path.join(path)
isExists = os.path.exists(local_save_path)
if not isExists:
os.makedirs(local_save_path)
return {'save_path': save_path, 'local_save_path': local_save_path}
由于开发环境,static还未处理,后期需要处理。
其他地方上传图片,使用了plopload,地址: https://blog.csdn.net/tang05709/article/details/104449432。所以之前是用的单文件接收图片,而且plopload多图片上传是分多次上传的,对于后端还是单文件,而wagneditor多文件上传是一次上传多个,所以需要多文件接收,django单文件接收和多文件接收是不一样的。
单文件
upfile = request.FILES.get('image', None)
多文件
upfiles = request.FILES.getlist('image', None)
由于返回数据格式不一样,所以需要做判断,我这里判断的唯一标准是updir,wangeditor的updir是detail,所以其他地方用到上传的不能使用detail,以免错误。