django 在admin中使用ueditor

代码部分参考了

http://www.yihaomen.com/article/python/238.htm

http://www.yihaomen.com/article/python/239.htm


大家也可以用DjangoUeditor


我的方法不需要安装,不过只是测试用,如果正式使用,最好还是要封装1个app


按照简单和复杂顺序写使用方法

1:下载ueditor到static目录下

2:urls.py添加

urlpatterns += patterns('',
    url(r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/js'}),
    url(r'^ueditor/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static/ueditor'}),
    url(r'^ueditor_imgup$','zhenman.ueditor.views.ueditor_ImgUp'),
    url(r'^ueditor_fileup$','zhenman.ueditor.views.ueditor_FileUp'),
    url(r'^ueditor_getRemoteImage$','zhenman.ueditor.views.ueditor_getRemoteImage'),
    url(r'^ueditor_scrawlUp$','zhenman.ueditor.views.ueditor_ScrawUp'),
    url(r'^ueditor_getMovie$','zhenman.ueditor.views.ueditor_getMovie'),
    url(r'^ueditor_imageManager$','zhenman.ueditor.views.ueditor_imageManager'),

    url(r'^upload/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'media'}),
)


3:static/js目录下新建ueditorCustomConfig.js代码

(function($) {
    $(document).ready(function($) {
        var uedes=new UE.ui.Editor();
        uedes.render(id_description);//description为model中的字段名称
        var ueCon=new UE.ui.Editor();
        ueCon.render(id_content);//content为model中的字段名
    });
})(django.jQuery);


4:在admin.py文件中要注册的对象模型中添加:

class Media:
        # js = ('/js/tinymce/tinymce.min.js', '/js/textareas.js')
        js = ('/ueditor/ueditor.all.js', '/ueditor/ueditor.config.js' , '/js/ueditorCustomConfig.js')

5:在app中新建ueditor包,在ueditor包下新建views.py文件。代码如下

#coding: utf-8
__author__ = 'watsy'

from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import Image
import os
import time
import urllib2
import uuid
import base64

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")
        MEDIA_ROOT = settings.MEDIA_ROOT[0] if isinstance(settings.MEDIA_ROOT , list) else settings.MEDIA_ROOT
        if not os.path.exists(MEDIA_ROOT + subfolder):
            os.makedirs(MEDIA_ROOT + 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 = MEDIA_ROOT + 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 = '/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):
    """ 涂鸦文件,处理 """
    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")
        MEDIA_ROOT = settings.MEDIA_ROOT[0] if isinstance(settings.MEDIA_ROOT , list) else settings.MEDIA_ROOT
        if not os.path.exists(MEDIA_ROOT + subfolder):
            os.makedirs(MEDIA_ROOT + subfolder)
        file_name = str(uuid.uuid1())
        path = str(subfolder + '/' + file_name + '.' + 'png')
        phisypath = MEDIA_ROOT + path
        f=open(phisypath,'wb+')
        f.write(base64.decodestring(base64Data))
        f.close()
        response=HttpResponse()
        response.write("{'url':'%s',state:'%s'}" % ('/upload/' + subfolder + '/' + file_name + '.' + 'png','SUCCESS'))
        return response

def listdir(path,filelist):
    """ 递归 得到所有图片文件信息 """
    phisypath = settings.MEDIA_ROOT[0] if isinstance(settings.MEDIA_ROOT , list) else settings.MEDIA_ROOT
    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,'/upload/').replace("//","/"))


@csrf_exempt
def ueditor_imageManager(request):
    """ 图片在线管理  """
    filelist=[]
    phisypath = settings.MEDIA_ROOT[0] if isinstance(settings.MEDIA_ROOT , list) else settings.MEDIA_ROOT
    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")
    MEDIA_ROOT = settings.MEDIA_ROOT[0] if isinstance(settings.MEDIA_ROOT , list) else settings.MEDIA_ROOT
    if not os.path.exists(MEDIA_ROOT + subfolder):
        os.makedirs(MEDIA_ROOT + 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 = MEDIA_ROOT + path
            piccontent= urllib2.urlopen(url).read()
            picfile=open(phisypath,'wb')
            picfile.write(piccontent)
            picfile.close()
            outlist.append('/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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值