在django中使用ueditor插件
来源:互联网 发布:怀化学院教务网络 编辑:程序博客网 时间:2024/06/03 10:48
试过tinymce以及强大的ckeditor,在django自带的后台管理中应用非常方便吗,但是如果使用自己写的后台或者将富文本编辑器应用在前台就会出现一系列问题。
后来,从网上查到一些资料,我使用了百度的ueditor编辑器插件,发现百度的这东西也很强大,虽然官网上只有php,.net,java三种语言的插件包,但是由于该插件是开源的,所以只要稍微改动一下就能在django中使用。我使用的 是ueditor的jsp版本
做一个html模板页面,在 head 部分,包含以下内容(路径要改成适合你自己的):
程序代码
<script type="text/javascript" charset="utf-8">
window.UEDITOR_HOME_URL = "/static/js/ueditor/";
</script>
<script type="text/javascript" charset="utf-8" src="/static/js/ueditor/editor_config.js"></script>
<script type="text/javascript" charset="utf-8" src="/static/js/ueditor/editor_all_min.js"></script>
<link rel="stylesheet" type="text/css" href="/static/js/ueditor/themes/default/ueditor.css"/>
模板的正文可以是如下内容,在<body>与</body>之间:
程序代码
<textarea id="content" name="content" style="width:575px;line-height:18px;"></textarea>
在html模板的结尾,在</body>之前,加上如下代码:
程序代码
<script>
var ue=new UE.ui.Editor();
ue.render('content');
</script>
到此,模板配置完毕。在django 工程的 urls.py 文件中配置一个url 路径,访问该模板页面,现在可以看到编辑器加载成功:
这是,点击上传图片图标,可以看到可以用本地上传,选择多个图片,但却无法上传,原因很简单,没有后台响应。所以需要些django后台来处理。
新建一个 app, 比如 Ueditor,看我的工程结构:
在里面建立一个 views.py 文件,代码如下:
程序代码
#coding:utf-8
'''
Created on 2012-8-29
@author: yihaomen.com
'''
from XieYin import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import Image
import os
import time
import urllib2
import uuid
def __myuploadfile(fileObj, source_pictitle, source_filename,fileorpic='pic'):
""" 一个公用的上传文件的处理 """
myresponse=""
if fileObj:
filename = fileObj.name.decode('utf-8', 'ignore')
fileExt = filename.split('.')[1]
file_name = str(uuid.uuid1())
subfolder = time.strftime("%Y%m")
if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
path = str(subfolder + '/' + file_name + '.' + fileExt)
if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png',"rar" ,"doc" ,"docx","zip","pdf","txt","swf","wmv"):
phisypath = settings.MEDIA_ROOT[0] + path
destination = open(phisypath, 'wb+')
for chunk in fileObj.chunks():
destination.write(chunk)
destination.close()
if fileorpic=='pic':
if fileExt.lower() in ('jpg', 'jpeg', 'bmp', 'gif', 'png'):
im = Image.open(phisypath)
im.thumbnail((720, 720))
im.save(phisypath)
real_url = '/static/upload/' + subfolder + '/' + file_name + '.' + fileExt
myresponse = "{'original':'%s','url':'%s','title':'%s','state':'%s'}" % (source_filename, real_url, source_pictitle, 'SUCCESS')
return myresponse
@csrf_exempt
def ueditor_ImgUp(request):
""" 上传图片 """
fileObj = request.FILES.get('upfile', None)
source_pictitle = request.POST.get('pictitle','')
source_filename = request.POST.get('fileName','')
response = HttpResponse()
myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'pic')
response.write(myresponse)
return response
@csrf_exempt
def ueditor_FileUp(request):
""" 上传文件 """
fileObj = request.FILES.get('upfile', None)
source_pictitle = request.POST.get('pictitle','')
source_filename = request.POST.get('fileName','')
response = HttpResponse()
myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'file')
response.write(myresponse)
return response
@csrf_exempt
def ueditor_ScrawUp(request):
""" 涂鸦文件,处理 """
pass
到目前为止,刚接触ueditor ,时间有限,我就做了上传文件和图片的。涂鸦,抓远程图片等,我在有时间的时候会补充出来。
在urls.py 中配置
程序代码
url(r'^ueditor_imgup$','XieYin.app.Ueditor.views.ueditor_ImgUp'),
url(r'^ueditor_fileup$','XieYin.app.Ueditor.views.ueditor_FileUp'),
修改百度ueditor 配置文件:editor_config.js
程序代码
//,imageUrl:URL+"jsp/imageUp.jsp"
,imageUrl:"/ueditor_imgup"
//图片上传提交地址
,imagePath:""
//附件上传配置区
,fileUrl:"/ueditor_fileup" //附件上传提交地址
,filePath:""
启动django程序
进入刚才的页面,选择上传图片.
到此,图片上传成功,其实文件也一样,只不过类型不同而已。
注意
程序确实实现了上传于ueditor 的继承。但还没有考虑到安全性,比如session的检查等。需要的,可以自己加上。
接下来顺便把其他的涂鸦什么的也做出来了,
在看测试代码之前,请注意在django程序的settings.py 中配置:
程序代码
MEDIA_ROOT = os.path.join(os.path.dirname(__file__),'static/upload/').replace('\\','/'),
这是我的配置,你可以改成适合你的配置。
今天又抽了一个小时,参考了下java 的代码,将上面的四个功能也实现,有需要的朋友可以参考. 同样在前面文章的基础上,在views.py 里面添加代码:
在线涂鸦
程序代码
@csrf_exempt
def ueditor_ScrawUp(request):
""" 涂鸦文件,处理 """
print request
param = request.POST.get("action",'')
fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"];
if param=='tmpImg':
fileObj = request.FILES.get('upfile', None)
source_pictitle = request.POST.get('pictitle','')
source_filename = request.POST.get('fileName','')
response = HttpResponse()
myresponse = __myuploadfile(fileObj, source_pictitle, source_filename,'pic')
myresponsedict=dict(myresponse)
url=myresponsedict.get('url','')
response.write("<script>parent.ue_callback('%s','%s')</script>" %(url,'SUCCESS'))
return response
else:
#========================base64上传的文件=======================
base64Data = request.POST.get('content','')
subfolder = time.strftime("%Y%m")
if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
file_name = str(uuid.uuid1())
path = str(subfolder + '/' + file_name + '.' + 'png')
phisypath = settings.MEDIA_ROOT[0] + path
f=open(phisypath,'wb+')
f.write(base64.decodestring(base64Data))
f.close()
response=HttpResponse()
response.write("{'url':'%s',state:'%s'}" % ('/static/upload/' + subfolder + '/' + file_name + '.' + 'png','SUCCESS'));
return response
图片的在线管理,浏览(目录递归浏览)
程序代码
def listdir(path,filelist):
""" 递归 得到所有图片文件信息 """
phisypath = settings.MEDIA_ROOT[0]
if os.path.isfile(path):
return '[]'
allFiles=os.listdir(path)
retlist=[]
for cfile in allFiles:
fileinfo={}
filepath=(path+os.path.sep+cfile).replace("\\","/").replace('//','/')
if os.path.isdir(filepath):
listdir(filepath,filelist)
else:
if cfile.endswith('.gif') or cfile.endswith('.png') or cfile.endswith('.jpg') or cfile.endswith('.bmp'):
filelist.append(filepath.replace(phisypath,'/static/upload/').replace("//","/"))
@csrf_exempt
def ueditor_imageManager(request):
""" 图片在线管理 """
filelist=[]
phisypath = settings.MEDIA_ROOT[0]
listdir(phisypath,filelist)
imgStr="ue_separate_ue".join(filelist)
response=HttpResponse()
response.write(imgStr)
return response
在线视频搜索
程序代码
@csrf_exempt
def ueditor_getMovie(request):
""" 获取视频数据的地址 """
content ="";
searchkey = request.POST.get("searchKey");
videotype = request.POST.get("videoType");
try:
url = "http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw="+ searchkey+"&pageNo=1&pageSize=20&channelId="+videotype+"&inDays=7&media=v&sort=s";
content=urllib2.urlopen(url).read()
except Exception,e:
pass
response=HttpResponse()
response.write(content);
return response
远程抓图,将别人网站的图片保存到本地,并显示出来
程序代码
@csrf_exempt
def ueditor_getRemoteImage(request):
print request
""" 把远程的图抓到本地,爬图 """
file_name = str(uuid.uuid1())
subfolder = time.strftime("%Y%m")
if not os.path.exists(settings.MEDIA_ROOT[0] + subfolder):
os.makedirs(settings.MEDIA_ROOT[0] + subfolder)
#====get request params=================================
urls = str(request.POST.get("upfile"));
urllist=urls.split("ue_separate_ue")
outlist=[]
#====request params end=================================
fileType = [".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"];
for url in urllist:
fileExt=""
for suffix in fileType:
if url.endswith(suffix):
fileExt=suffix
break;
if fileExt=='':
continue
else:
path = str(subfolder + '/' + file_name + '.' + fileExt)
phisypath = settings.MEDIA_ROOT[0] + path
piccontent= urllib2.urlopen(url).read()
picfile=open(phisypath,'wb')
picfile.write(piccontent)
picfile.close()
outlist.append('/static/upload/' + subfolder + '/' + file_name + '.' + fileExt)
outlist="ue_separate_ue".join(outlist)
response=HttpResponse()
myresponse="{'url':'%s','tip':'%s','srcUrl':'%s'}" % (outlist,'成功',urls)
response.write(myresponse);
return response
更新 urls.py
程序代码
url(r'^ueditor_imgup$','MyNet.app.Ueditor.views.ueditor_ImgUp'),
url(r'^ueditor_fileup$','MyNet.app.Ueditor.views.ueditor_FileUp'),
url(r'^ueditor_getRemoteImage$','MyNet.app.Ueditor.views.ueditor_getRemoteImage'),
url(r'^ueditor_scrawlUp$','MyNet.app.Ueditor.views.ueditor_ScrawUp'),
url(r'^ueditor_getMovie$','MyNet.app.Ueditor.views.ueditor_getMovie'),
url(r'^ueditor_imageManager$','MyNet.app.Ueditor.views.ueditor_imageManager'),
更改ueditor config 配置文件
程序代码
,imageUrl:"/ueditor_imgup"
,imagePath:""
//涂鸦图片配置区
,scrawlUrl:"/ueditor_scrawlUp"
,scrawlPath:""
//附件上传配置区
,fileUrl:"/ueditor_fileup"
,filePath:""
//远程抓取配置区
,catcherUrl:"/ueditor_getRemoteImage"
,catcherPath:""
//图片在线管理配置区
,imageManagerUrl:"/ueditor_imageManager"
,imageManagerPath:""
//屏幕截图配置区
,snapscreenHost: '127.0.0.1'
,snapscreenServerUrl: "/ueditor_imgup"
,snapscreenPath: ""
//word转存配置区
,wordImageUrl:"/ueditor_imgup"
,wordImagePath:""
//获取视频数据的地址
,getMovieUrl:"/ueditor_getMovie"
至此,所有在django使用ueditor所需的配置已经全部完成,注意view视图中的文件路径要改成自己想存的路径,还有setting中的STATIC_ROOT和MEDIA_ROOT一定要配置正确,否则图片及其他文件不能正常显示和上传
另外:在js中获取编辑器内容使用ue.getContent(),对其赋值使用ue.setContent(323.)
参考:http://www.yihaomen.com/article/python/239.htm
http://www.yihaomen.com/article/python/238.htm
http://www.jb51.net/article/51855.htm
http://down.admin5.com/info/2014/0729/112836.html
0 0
- 在django中使用ueditor插件
- django 在admin中使用ueditor
- 在django xadmin中使用 Ueditor
- django 在admin中使用ueditor
- 在Django Xadmin中集成Ueditor
- 在Ueditor 1.4.3中自定义插件
- Django 使用UEditor
- Django使用Ueditor
- 使用ueditor插件
- 使用UEditor在门户中添加公告
- 如何在IntelliJ IDEA 中配置ueditor富文本插件
- 在Django中使用databrowse
- 在django中使用memcache
- 在Django中使用group_by
- South在Django中使用
- 在Django中使用markdown
- 在Django中使用markdown
- 在Django中使用markdown
- 83 js 如何正确传递DOM元素的指针 选择器内参数为变量 论js函数的简化 seajs用法
- Tomcat集群之Session复制配置
- TopCoder - SRM521 div1 500 RangeSquaredSubsets
- HDU 5157 Harry and magic string(Manacher)
- 欢迎使用CSDN-markdown编辑器
- 在django中使用ueditor插件
- 继承和协议的关系
- C++内存分配方式详解——堆、栈、自由存储区、全局/静态存储区和常量存储区
- solr4.7新建core
- java - mysql连接
- 图的深度优先搜索(DFS)
- Tomcat 不同web项目session共享.
- win8 系统无法启动
- 字符串类的实现:构造函数、析构函数、复制构造函数和赋值操作符