Procházet zdrojové kódy

合并历史修改

Weizhong Tu před 10 roky
rodič
revize
b03366136c

+ 1 - 1
DjangoUeditor/__init__.py

@@ -1,6 +1,6 @@
 # coding:utf-8
 import urllib
-import DjangoUeditor.settings as USettings
+from . import settings as USettings
 
 
 class UEditorEventHandler(object):

+ 23 - 16
DjangoUeditor/forms.py

@@ -1,34 +1,41 @@
-#coding: utf-8
+# coding: utf-8
 
 from django import forms
 from widgets import UEditorWidget
 from DjangoUeditor.models import UEditorField as ModelUEditorField
 
+
 class UEditorField(forms.CharField):
-    def __init__(self,label,width=600, height=300, toolbars="full",imagePath="", filePath="",upload_settings={},settings={},command=None ,event_handler=None,*args,**kwargs):
-        uSettings=locals().copy()
-        del uSettings["self"],uSettings["label"],uSettings["args"],uSettings["kwargs"]
-        kwargs["widget"]=UEditorWidget(attrs=uSettings)
-        kwargs["label"]=label
-        super(UEditorField,self).__init__( *args, **kwargs)
-
-def UpdateUploadPath(model_form,model_inst=None):
+
+    def __init__(self, label, width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={}, settings={}, command=None, event_handler=None, *args, **kwargs):
+        uSettings = locals().copy()
+        del uSettings["self"], uSettings[
+            "label"], uSettings["args"], uSettings["kwargs"]
+        kwargs["widget"] = UEditorWidget(attrs=uSettings)
+        kwargs["label"] = label
+        super(UEditorField, self).__init__(*args, **kwargs)
+
+
+def UpdateUploadPath(model_form, model_inst=None):
     """ 遍历model字段,如果是UEditorField则需要重新计算路径 """
-    if model_inst is not  None:
+    if model_inst is not None:
         try:
             for field in model_inst._meta.fields:
                 if isinstance(field, ModelUEditorField):
-                    model_form.__getitem__(field.name).field.widget.recalc_path(model_inst)
+                    model_form.__getitem__(
+                        field.name).field.widget.recalc_path(model_inst)
         except:
             pass
 
+
 class UEditorModelForm(forms.ModelForm):
-    def __init__(self,*args,**kwargs):
-        super(UEditorModelForm,self).__init__(*args,**kwargs)
+
+    def __init__(self, *args, **kwargs):
+        super(UEditorModelForm, self).__init__(*args, **kwargs)
         try:
-            if kwargs.has_key("instance"):
-                UpdateUploadPath(self,kwargs["instance"])
+            if 'instance' in kwargs:
+                UpdateUploadPath(self, kwargs["instance"])
             else:
-                UpdateUploadPath(self,None)
+                UpdateUploadPath(self, None)
         except Exception:
             pass

+ 1 - 1
DjangoUeditor/models.py

@@ -1,7 +1,7 @@
 #coding: utf-8
 from django.db import models
 from django.contrib.admin import widgets as admin_widgets
-from .widgets import UEditorWidget,AdminUEditorWidget
+from .widgets import UEditorWidget, AdminUEditorWidget
 
 
 class UEditorField(models.TextField):

+ 85 - 83
DjangoUeditor/readme.txt

@@ -1,112 +1,114 @@
-#coding:utf-8
-from django.conf import settings as gSettings   #全局设置
-
-#工具栏样式,可以添加任意多的模式
-TOOLBARS_SETTINGS={
-    "besttome":[['source','undo', 'redo','bold', 'italic', 'underline','forecolor', 'backcolor','superscript','subscript',"justifyleft","justifycenter","justifyright","insertorderedlist","insertunorderedlist","blockquote",'formatmatch',"removeformat",'autotypeset','inserttable',"pasteplain","wordimage","searchreplace","map","preview","fullscreen"], ['insertcode','paragraph',"fontfamily","fontsize",'link', 'unlink','insertimage','insertvideo','attachment','emotion',"date","time"]],
-    "mini":[['source','|','undo', 'redo', '|','bold', 'italic', 'underline','formatmatch','autotypeset', '|', 'forecolor', 'backcolor','|', 'link', 'unlink','|','simpleupload','attachment']],
-    "normal":[['source','|','undo', 'redo', '|','bold', 'italic', 'underline','removeformat', 'formatmatch','autotypeset', '|', 'forecolor', 'backcolor','|', 'link', 'unlink','|','simpleupload', 'emotion','attachment', '|','inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']]
+# coding:utf-8
+from django.conf import settings as gSettings  # 全局设置
+
+# 工具栏样式,可以添加任意多的模式
+TOOLBARS_SETTINGS = {
+    "besttome": [['source', 'undo', 'redo', 'bold', 'italic', 'underline', 'forecolor', 'backcolor', 'superscript', 'subscript', "justifyleft", "justifycenter", "justifyright", "insertorderedlist", "insertunorderedlist", "blockquote", 'formatmatch', "removeformat", 'autotypeset', 'inserttable', "pasteplain", "wordimage", "searchreplace", "map", "preview", "fullscreen"], ['insertcode', 'paragraph', "fontfamily", "fontsize", 'link', 'unlink', 'insertimage', 'insertvideo', 'attachment', 'emotion', "date", "time"]],
+    "mini": [['source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'formatmatch', 'autotypeset', '|', 'forecolor', 'backcolor', '|', 'link', 'unlink', '|', 'simpleupload', 'attachment']],
+    "normal": [['source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', '|', 'forecolor', 'backcolor', '|', 'link', 'unlink', '|', 'simpleupload', 'emotion', 'attachment', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']]
 }
 
-#默认的Ueditor设置,请参见ueditor.config.js
-UEditorSettings={
-    "toolbars":TOOLBARS_SETTINGS["normal"],
-    "autoFloatEnabled":False,
-    "defaultPathFormat":"%(basename)s_%(datetime)s_%(rnd)s.%(extname)s"   #默认保存上传文件的命名方式
+# 默认的Ueditor设置,请参见ueditor.config.js
+UEditorSettings = {
+    "toolbars": TOOLBARS_SETTINGS["normal"],
+    "autoFloatEnabled": False,
+    # 默认保存上传文件的命名方式
+    "defaultPathFormat": "%(basename)s_%(datetime)s_%(rnd)s.%(extname)s"
 }
-#请参阅php文件夹里面的config.json进行配置
-UEditorUploadSettings={
-   #上传图片配置项
-    "imageActionName": "uploadimage", #执行上传图片的action名称
-    "imageMaxSize": 10485760, #上传大小限制,单位B,10M
-    "imageFieldName": "upfile", #* 提交的图片表单名称 */
-    "imageUrlPrefix":"",
-    "imagePathFormat":"",
-    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], #上传图片格式显示
-
-    #涂鸦图片上传配置项 */
-    "scrawlActionName": "uploadscrawl", #执行上传涂鸦的action名称 */
-    "scrawlFieldName": "upfile", #提交的图片表单名称 */
-    "scrawlMaxSize": 10485760, #上传大小限制,单位B  10M
-    "scrawlUrlPrefix":"",
-    "scrawlPathFormat":"",
-
-    #截图工具上传 */
-    "snapscreenActionName": "uploadimage", #执行上传截图的action名称 */
-    "snapscreenPathFormat":"",
-    "snapscreenUrlPrefix":"",
-
-    #抓取远程图片配置 */
+# 请参阅php文件夹里面的config.json进行配置
+UEditorUploadSettings = {
+    # 上传图片配置项
+    "imageActionName": "uploadimage",  # 执行上传图片的action名称
+    "imageMaxSize": 10485760,  # 上传大小限制,单位B,10M
+    "imageFieldName": "upfile",  # * 提交的图片表单名称 */
+    "imageUrlPrefix": "",
+    "imagePathFormat": "",
+    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],  # 上传图片格式显示
+
+    # 涂鸦图片上传配置项 */
+    "scrawlActionName": "uploadscrawl",  # 执行上传涂鸦的action名称 */
+    "scrawlFieldName": "upfile",  # 提交的图片表单名称 */
+    "scrawlMaxSize": 10485760,  # 上传大小限制,单位B  10M
+    "scrawlUrlPrefix": "",
+    "scrawlPathFormat": "",
+
+    # 截图工具上传 */
+    "snapscreenActionName": "uploadimage",  # 执行上传截图的action名称 */
+    "snapscreenPathFormat": "",
+    "snapscreenUrlPrefix": "",
+
+    # 抓取远程图片配置 */
     "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
-    "catcherPathFormat":"",
-    "catcherActionName": "catchimage", #执行抓取远程图片的action名称 */
-    "catcherFieldName": "source", #提交的图片列表表单名称 */
-    "catcherMaxSize": 10485760, #上传大小限制,单位B */
-    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], #抓取图片格式显示 */
-    "catcherUrlPrefix":"",
-    #上传视频配置 */
-    "videoActionName": "uploadvideo", #执行上传视频的action名称 */
-    "videoPathFormat":"",
-    "videoFieldName": "upfile", # 提交的视频表单名称 */
-    "videoMaxSize": 102400000, #上传大小限制,单位B,默认100MB */
-    "videoUrlPrefix":"",
+    "catcherPathFormat": "",
+    "catcherActionName": "catchimage",  # 执行抓取远程图片的action名称 */
+    "catcherFieldName": "source",  # 提交的图片列表表单名称 */
+    "catcherMaxSize": 10485760,  # 上传大小限制,单位B */
+    # 抓取图片格式显示 */
+    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
+    "catcherUrlPrefix": "",
+    # 上传视频配置 */
+    "videoActionName": "uploadvideo",  # 执行上传视频的action名称 */
+    "videoPathFormat": "",
+    "videoFieldName": "upfile",  # 提交的视频表单名称 */
+    "videoMaxSize": 102400000,  # 上传大小限制,单位B,默认100MB */
+    "videoUrlPrefix": "",
     "videoAllowFiles": [
         ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
-        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], #上传视频格式显示 */
-
-    #上传文件配置 */
-    "fileActionName": "uploadfile", #controller里,执行上传视频的action名称 */
-    "filePathFormat":"",
-    "fileFieldName": "upfile",#提交的文件表单名称 */
-    "fileMaxSize": 204800000, #上传大小限制,单位B,200MB */
-    "fileUrlPrefix": "",#文件访问路径前缀 */
+        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],  # 上传视频格式显示 */
+
+    # 上传文件配置 */
+    "fileActionName": "uploadfile",  # controller里,执行上传视频的action名称 */
+    "filePathFormat": "",
+    "fileFieldName": "upfile",  # 提交的文件表单名称 */
+    "fileMaxSize": 204800000,  # 上传大小限制,单位B,200MB */
+    "fileUrlPrefix": "",  # 文件访问路径前缀 */
     "fileAllowFiles": [
         ".png", ".jpg", ".jpeg", ".gif", ".bmp",
         ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
         ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
         ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
         ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
-    ], #上传文件格式显示 */
-
-    #列出指定目录下的图片 */
-    "imageManagerActionName": "listimage", #执行图片管理的action名称 */
-    "imageManagerListPath":"",
-    "imageManagerListSize": 30, #每次列出文件数量 */
-    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], #列出的文件类型 */
-    "imageManagerUrlPrefix": "",#图片访问路径前缀 */
-
-    #列出指定目录下的文件 */
-    "fileManagerActionName": "listfile", #执行文件管理的action名称 */
-    "fileManagerListPath":"",
+    ],  # 上传文件格式显示 */
+
+    # 列出指定目录下的图片 */
+    "imageManagerActionName": "listimage",  # 执行图片管理的action名称 */
+    "imageManagerListPath": "",
+    "imageManagerListSize": 30,  # 每次列出文件数量 */
+    # 列出的文件类型 */
+    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
+    "imageManagerUrlPrefix": "",  # 图片访问路径前缀 */
+
+    # 列出指定目录下的文件 */
+    "fileManagerActionName": "listfile",  # 执行文件管理的action名称 */
+    "fileManagerListPath": "",
     "fileManagerUrlPrefix": "",
-    "fileManagerListSize": 30, #每次列出文件数量 */
+    "fileManagerListSize": 30,  # 每次列出文件数量 */
     "fileManagerAllowFiles": [
-        ".png", ".jpg", ".jpeg", ".gif", ".bmp",".tif",".psd"
+        ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".psd"
         ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
         ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
         ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
         ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml",
-        ".exe",".com",".dll",".msi"
-    ] #列出的文件类型 */
+        ".exe", ".com", ".dll", ".msi"
+    ]  # 列出的文件类型 */
 }
 
 
-#更新配置:从用户配置文件settings.py重新读入配置UEDITOR_SETTINGS,覆盖默认
+# 更新配置:从用户配置文件settings.py重新读入配置UEDITOR_SETTINGS,覆盖默认
 def UpdateUserSettings():
-    UserSettings=getattr(gSettings,"UEDITOR_SETTINGS",{}).copy()
-    if "config" in UserSettings: UEditorSettings.update(UserSettings["config"])
-    if "upload" in UserSettings: UEditorUploadSettings.update(UserSettings["upload"])
+    UserSettings = getattr(gSettings, "UEDITOR_SETTINGS", {}).copy()
+    if 'config' in UserSettings:
+        UEditorSettings.update(UserSettings["config"])
+    if 'upload' in UserSettings:
+        UEditorUploadSettings.update(UserSettings["upload"])
 
-#读取用户Settings文件并覆盖默认配置
+# 读取用户Settings文件并覆盖默认配置
 UpdateUserSettings()
 
 
-#取得配置项参数
-def GetUeditorSettings(key,default=None):
-    if UEditorSettings.has_key(key):
+# 取得配置项参数
+def GetUeditorSettings(key, default=None):
+    if key in UEditorSettings:
         return UEditorSettings[key]
     else:
         return default
-
-
-

+ 6 - 4
DjangoUeditor/static/ueditor/UEditorSnapscreen.exe

@@ -1,12 +1,14 @@
-#coding:utf-8
+# coding:utf-8
 from django import VERSION
-if VERSION[0:2]>(1,3):
+
+if VERSION[0:2] > (1, 3):
     from django.conf.urls import patterns, url
 else:
     from django.conf.urls.defaults import patterns, url
 
+
 from .views import get_ueditor_controller
 
 urlpatterns = patterns('',
-    url(r'^controller/$',get_ueditor_controller)
-)
+    url(r'^controller/$', get_ueditor_controller)
+)

+ 63 - 51
DjangoUeditor/utils.py

@@ -1,94 +1,105 @@
-#coding: utf-8
+# coding: utf-8
+# 文件大小类
+from django.utils import six
+
+if six.PY3:
+    long = int
+
 
-#文件大小类
 class FileSize():
-    SIZE_UNIT={"Byte":1,"KB":1024,"MB":1048576,"GB":1073741824,"TB":1099511627776L}
-    def __init__(self,size):
-        self.size=long(FileSize.Format(size))
+    SIZE_UNIT = {"Byte": 1, "KB": 1024, "MB": 1048576, "GB": 1073741824, "TB": 1099511627776}
+
+    def __init__(self, size):
+        self.size = long(FileSize.Format(size))
 
     @staticmethod
     def Format(size):
         import re
-        if isinstance(size,int) or isinstance(size,long):
+        if isinstance(size, six.integer_types):
             return size
         else:
-            if not isinstance(size,str):
+            if not isinstance(size, str):
                 return 0
             else:
-                oSize=size.lstrip().upper().replace(" ","")
-                pattern=re.compile(r"(\d*\.?(?=\d)\d*)(byte|kb|mb|gb|tb)",re.I)
-                match=pattern.match(oSize)
+                oSize = size.lstrip().upper().replace(" ", "")
+                pattern = re.compile(
+                    r"(\d*\.?(?=\d)\d*)(byte|kb|mb|gb|tb)", re.I)
+                match = pattern.match(oSize)
                 if match:
-                    m_size, m_unit=match.groups()
-                    if m_size.find(".")==-1:
-                        m_size=long(m_size)
+                    m_size, m_unit = match.groups()
+                    if m_size.find(".") == -1:
+                        m_size = long(m_size)
                     else:
-                        m_size=float(m_size)
-                    if m_unit!="BYTE":
-                        return m_size*FileSize.SIZE_UNIT[m_unit]
+                        m_size = float(m_size)
+                    if m_unit != "BYTE":
+                        return m_size * FileSize.SIZE_UNIT[m_unit]
                     else:
                         return m_size
                 else:
                     return 0
 
-    #返回字节为单位的值
+    # 返回字节为单位的值
     @property
     def size(self):
         return self.size
+
     @size.setter
-    def size(self,newsize):
+    def size(self, newsize):
         try:
-            self.size=long(newsize)
+            self.size = long(newsize)
         except:
-            self.size=0
+            self.size = 0
 
-    #返回带单位的自动值
+    # 返回带单位的自动值
     @property
     def FriendValue(self):
-        if self.size<FileSize.SIZE_UNIT["KB"]:
-            unit="Byte"
-        elif self.size<FileSize.SIZE_UNIT["MB"]:
-            unit="KB"
-        elif self.size<FileSize.SIZE_UNIT["GB"]:
-            unit="MB"
-        elif self.size<FileSize.SIZE_UNIT["TB"]:
-            unit="GB"
+        if self.size < FileSize.SIZE_UNIT["KB"]:
+            unit = "Byte"
+        elif self.size < FileSize.SIZE_UNIT["MB"]:
+            unit = "KB"
+        elif self.size < FileSize.SIZE_UNIT["GB"]:
+            unit = "MB"
+        elif self.size < FileSize.SIZE_UNIT["TB"]:
+            unit = "GB"
         else:
-            unit="TB"
+            unit = "TB"
 
-        if (self.size % FileSize.SIZE_UNIT[unit])==0:
-            return "%s%s" % ((self.size / FileSize.SIZE_UNIT[unit]),unit)
+        if (self.size % FileSize.SIZE_UNIT[unit]) == 0:
+            return "%s%s" % ((self.size / FileSize.SIZE_UNIT[unit]), unit)
         else:
-            return "%0.2f%s" % (round(float(self.size) /float(FileSize.SIZE_UNIT[unit]) ,2),unit)
+            return "%0.2f%s" % (round(float(self.size) / float(FileSize.SIZE_UNIT[unit]), 2), unit)
 
     def __str__(self):
         return self.FriendValue
 
-    #相加
+    # 相加
     def __add__(self, other):
-        if isinstance(other,FileSize):
-            return FileSize(other.size+self.size)
+        if isinstance(other, FileSize):
+            return FileSize(other.size + self.size)
         else:
-            return FileSize(FileSize(other).size+self.size)
+            return FileSize(FileSize(other).size + self.size)
+
     def __sub__(self, other):
-        if isinstance(other,FileSize):
-            return FileSize(self.size-other.size)
+        if isinstance(other, FileSize):
+            return FileSize(self.size - other.size)
         else:
-            return FileSize(self.size-FileSize(other).size)
+            return FileSize(self.size - FileSize(other).size)
+
     def __gt__(self, other):
-        if isinstance(other,FileSize):
-            if self.size>other.size:
+        if isinstance(other, FileSize):
+            if self.size > other.size:
                 return True
             else:
                 return False
         else:
-            if self.size>FileSize(other).size:
+            if self.size > FileSize(other).size:
                 return True
             else:
                 return False
+
     def __lt__(self, other):
-        if isinstance(other,FileSize):
-            if other.size>self.size:
+        if isinstance(other, FileSize):
+            if other.size > self.size:
                 return True
             else:
                 return False
@@ -97,20 +108,22 @@ class FileSize():
                 return True
             else:
                 return False
+
     def __ge__(self, other):
-        if isinstance(other,FileSize):
-            if self.size>=other.size:
+        if isinstance(other, FileSize):
+            if self.size >= other.size:
                 return True
             else:
                 return False
         else:
-            if self.size>=FileSize(other).size:
+            if self.size >= FileSize(other).size:
                 return True
             else:
                 return False
+
     def __le__(self, other):
-        if isinstance(other,FileSize):
-            if other.size>=self.size:
+        if isinstance(other, FileSize):
+            if other.size >= self.size:
                 return True
             else:
                 return False
@@ -119,4 +132,3 @@ class FileSize():
                 return True
             else:
                 return False
-

+ 220 - 190
DjangoUeditor/views.py

@@ -1,55 +1,64 @@
-#coding:utf-8
+# coding:utf-8
 from importlib import import_module
 from django.http import HttpResponse
-import DjangoUeditor.settings as USettings
+from . import settings as USettings
 import os
 import json
 from django.views.decorators.csrf import csrf_exempt
-from datetime import datetime
+import datetime
 import random
 import urllib
+from django.utils import six
+
+if six.PY3:
+    long = int
+
 
 def get_path_format_vars():
     return {
-        "year":datetime.datetime.now().strftime("%Y"),
-        "month":datetime.datetime.now().strftime("%m"),
-        "day":datetime.datetime.now().strftime("%d"),
+        "year": datetime.datetime.now().strftime("%Y"),
+        "month": datetime.datetime.now().strftime("%m"),
+        "day": datetime.datetime.now().strftime("%d"),
         "date": datetime.datetime.now().strftime("%Y%m%d"),
-        "time":datetime.datetime.now().strftime("%H%M%S"),
-        "datetime":datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
-        "rnd":random.randrange(100,999)
+        "time": datetime.datetime.now().strftime("%H%M%S"),
+        "datetime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
+        "rnd": random.randrange(100, 999)
     }
 
-#保存上传的文件
-def save_upload_file(PostFile,FilePath):
+# 保存上传的文件
+
+
+def save_upload_file(PostFile, FilePath):
     try:
         f = open(FilePath, 'wb')
         for chunk in PostFile.chunks():
             f.write(chunk)
     except Exception as E:
         f.close()
-        return u"写入文件错误:"+ E.message
+        return u"写入文件错误:" + E.message
     f.close()
     return u"SUCCESS"
 
 
 @csrf_exempt
 def get_ueditor_settings(request):
-    return HttpResponse(json.dumps(USettings.UEditorUploadSettings,ensure_ascii=False), content_type="application/javascript")
+    return HttpResponse(json.dumps(USettings.UEditorUploadSettings, ensure_ascii=False), content_type="application/javascript")
+
+
 @csrf_exempt
 def get_ueditor_controller(request):
     """获取ueditor的后端URL地址    """
 
-    action=request.GET.get("action","")
-    reponseAction={
-        "config":get_ueditor_settings,
-        "uploadimage":UploadFile,
-        "uploadscrawl":UploadFile,
-        "uploadvideo":UploadFile,
-        "uploadfile":UploadFile,
-        "catchimage":catcher_remote_image,
-        "listimage":list_files,
-        "listfile":list_files
+    action = request.GET.get("action", "")
+    reponseAction = {
+        "config": get_ueditor_settings,
+        "uploadimage": UploadFile,
+        "uploadscrawl": UploadFile,
+        "uploadvideo": UploadFile,
+        "uploadfile": UploadFile,
+        "catchimage": catcher_remote_image,
+        "listimage": list_files,
+        "listfile": list_files
     }
     return reponseAction[action](request)
 
@@ -57,64 +66,66 @@ def get_ueditor_controller(request):
 @csrf_exempt
 def list_files(request):
     """列出文件"""
-    if request.method!="GET":
-        return  HttpResponse(json.dumps(u"{'state:'ERROR'}") ,content_type="application/javascript")
-    #取得动作
-    action=request.GET.get("action","listimage")
-
-    allowFiles={
-        "listfile":USettings.UEditorUploadSettings.get("fileManagerAllowFiles",[]),
-        "listimage":USettings.UEditorUploadSettings.get("imageManagerAllowFiles",[])
+    if request.method != "GET":
+        return HttpResponse(json.dumps(u"{'state:'ERROR'}"), content_type="application/javascript")
+    # 取得动作
+    action = request.GET.get("action", "listimage")
+
+    allowFiles = {
+        "listfile": USettings.UEditorUploadSettings.get("fileManagerAllowFiles", []),
+        "listimage": USettings.UEditorUploadSettings.get("imageManagerAllowFiles", [])
     }
-    listSize={
-        "listfile":USettings.UEditorUploadSettings.get("fileManagerListSize",""),
-        "listimage":USettings.UEditorUploadSettings.get("imageManagerListSize","")
+    listSize = {
+        "listfile": USettings.UEditorUploadSettings.get("fileManagerListSize", ""),
+        "listimage": USettings.UEditorUploadSettings.get("imageManagerListSize", "")
     }
-    listpath={
-        "listfile":USettings.UEditorUploadSettings.get("fileManagerListPath",""),
-        "listimage":USettings.UEditorUploadSettings.get("imageManagerListPath","")
+    listpath = {
+        "listfile": USettings.UEditorUploadSettings.get("fileManagerListPath", ""),
+        "listimage": USettings.UEditorUploadSettings.get("imageManagerListPath", "")
     }
-    #取得参数
-    list_size=long(request.GET.get("size",listSize[action]))
-    list_start=long(request.GET.get("start",0))
-
-    files=[]
-    root_path=os.path.join(USettings.gSettings.MEDIA_ROOT,listpath[action]).replace("\\","/")
-    files=get_files(root_path,root_path,allowFiles[action])
-
-    if (len(files)==0):
-        return_info={
-            "state":u"未找到匹配文件!",
-            "list":[],
-            "start":list_start,
-            "total":0
+    # 取得参数
+    list_size = long(request.GET.get("size", listSize[action]))
+    list_start = long(request.GET.get("start", 0))
+
+    files = []
+    root_path = os.path.join(
+        USettings.gSettings.MEDIA_ROOT, listpath[action]).replace("\\", "/")
+    files = get_files(root_path, root_path, allowFiles[action])
+
+    if (len(files) == 0):
+        return_info = {
+            "state": u"未找到匹配文件!",
+            "list": [],
+            "start": list_start,
+            "total": 0
         }
     else:
-        return_info={
-            "state":"SUCCESS",
-            "list":files[list_start:list_start+list_size],
-            "start":list_start,
-            "total":len(files)
+        return_info = {
+            "state": "SUCCESS",
+            "list": files[list_start:list_start + list_size],
+            "start": list_start,
+            "total": len(files)
         }
 
-    return HttpResponse(json.dumps(return_info),content_type="application/javascript")
+    return HttpResponse(json.dumps(return_info), content_type="application/javascript")
 
 
-def get_files(root_path,cur_path, allow_types=[]):
+def get_files(root_path, cur_path, allow_types=[]):
     files = []
     items = os.listdir(cur_path)
     for item in items:
-        item=unicode(item)
-        item_fullname = os.path.join(root_path,cur_path, item).replace("\\", "/")
+        item = unicode(item)
+        item_fullname = os.path.join(
+            root_path, cur_path, item).replace("\\", "/")
         if os.path.isdir(item_fullname):
-            files.extend(get_files(root_path,item_fullname, allow_types))
+            files.extend(get_files(root_path, item_fullname, allow_types))
         else:
             ext = os.path.splitext(item_fullname)[1]
-            is_allow_list= (len(allow_types)==0) or (ext in allow_types)
+            is_allow_list = (len(allow_types) == 0) or (ext in allow_types)
             if is_allow_list:
                 files.append({
-                    "url":urllib.basejoin(USettings.gSettings.MEDIA_URL ,os.path.join(os.path.relpath(cur_path,root_path),item).replace("\\","/" )),
-                    "mtime":os.path.getmtime(item_fullname)
+                    "url": urllib.basejoin(USettings.gSettings.MEDIA_URL, os.path.join(os.path.relpath(cur_path, root_path), item).replace("\\", "/")),
+                    "mtime": os.path.getmtime(item_fullname)
                 })
 
     return files
@@ -123,185 +134,204 @@ def get_files(root_path,cur_path, allow_types=[]):
 @csrf_exempt
 def UploadFile(request):
     """上传文件"""
-    if not request.method=="POST":
-        return  HttpResponse(json.dumps(u"{'state:'ERROR'}"),content_type="application/javascript")
-
-    state="SUCCESS"
-    action=request.GET.get("action")
-    #上传文件
-    upload_field_name={
-        "uploadfile":"fileFieldName","uploadimage":"imageFieldName",
-        "uploadscrawl":"scrawlFieldName","catchimage":"catcherFieldName",
-        "uploadvideo":"videoFieldName",
+    if not request.method == "POST":
+        return HttpResponse(json.dumps(u"{'state:'ERROR'}"), content_type="application/javascript")
+
+    state = "SUCCESS"
+    action = request.GET.get("action")
+    # 上传文件
+    upload_field_name = {
+        "uploadfile": "fileFieldName", "uploadimage": "imageFieldName",
+        "uploadscrawl": "scrawlFieldName", "catchimage": "catcherFieldName",
+        "uploadvideo": "videoFieldName",
     }
-    UploadFieldName=request.GET.get(upload_field_name[action],USettings.UEditorUploadSettings.get(action,"upfile"))
+    UploadFieldName = request.GET.get(
+        upload_field_name[action], USettings.UEditorUploadSettings.get(action, "upfile"))
 
-    #上传涂鸦,涂鸦是采用base64编码上传的,需要单独处理
-    if action=="uploadscrawl":
-        upload_file_name="scrawl.png"
-        upload_file_size=0
+    # 上传涂鸦,涂鸦是采用base64编码上传的,需要单独处理
+    if action == "uploadscrawl":
+        upload_file_name = "scrawl.png"
+        upload_file_size = 0
     else:
-        #取得上传的文件
-        file=request.FILES.get(UploadFieldName,None)
-        if file is None:return  HttpResponse(json.dumps(u"{'state:'ERROR'}") ,content_type="application/javascript")
-        upload_file_name=file.name
-        upload_file_size=file.size
-
-    #取得上传的文件的原始名称
-    upload_original_name,upload_original_ext=os.path.splitext(upload_file_name)
-
-    #文件类型检验
-    upload_allow_type={
-        "uploadfile":"fileAllowFiles",
-        "uploadimage":"imageAllowFiles",
-        "uploadvideo":"videoAllowFiles"
+        # 取得上传的文件
+        file = request.FILES.get(UploadFieldName, None)
+        if file is None:
+            return HttpResponse(json.dumps(u"{'state:'ERROR'}"), content_type="application/javascript")
+        upload_file_name = file.name
+        upload_file_size = file.size
+
+    # 取得上传的文件的原始名称
+    upload_original_name, upload_original_ext = os.path.splitext(
+        upload_file_name)
+
+    # 文件类型检验
+    upload_allow_type = {
+        "uploadfile": "fileAllowFiles",
+        "uploadimage": "imageAllowFiles",
+        "uploadvideo": "videoAllowFiles"
     }
-    if upload_allow_type.has_key(action):
-        allow_type= list(request.GET.get(upload_allow_type[action],USettings.UEditorUploadSettings.get(upload_allow_type[action],"")))
-        if not upload_original_ext  in allow_type:
-            state=u"服务器不允许上传%s类型的文件。" % upload_original_ext
-
-    #大小检验
-    upload_max_size={
-        "uploadfile":"filwMaxSize",
-        "uploadimage":"imageMaxSize",
-        "uploadscrawl":"scrawlMaxSize",
-        "uploadvideo":"videoMaxSize"
+    if action in upload_allow_type:
+        allow_type = list(request.GET.get(upload_allow_type[
+                          action], USettings.UEditorUploadSettings.get(upload_allow_type[action], "")))
+        if not upload_original_ext in allow_type:
+            state = u"服务器不允许上传%s类型的文件。" % upload_original_ext
+
+    # 大小检验
+    upload_max_size = {
+        "uploadfile": "filwMaxSize",
+        "uploadimage": "imageMaxSize",
+        "uploadscrawl": "scrawlMaxSize",
+        "uploadvideo": "videoMaxSize"
     }
-    max_size=long(request.GET.get(upload_max_size[action],USettings.UEditorUploadSettings.get(upload_max_size[action],0)))
-    if  max_size!=0:
-        from utils import FileSize
-        MF=FileSize(max_size)
-        if upload_file_size>MF.size:
-            state=u"上传文件大小不允许超过%s。" % MF.FriendValue
-
-    #检测保存路径是否存在,如果不存在则需要创建
-    upload_path_format={
-        "uploadfile":"filePathFormat",
-        "uploadimage":"imagePathFormat",
-        "uploadscrawl":"scrawlPathFormat",
-        "uploadvideo":"videoPathFormat"
+    max_size = long(request.GET.get(upload_max_size[
+                    action], USettings.UEditorUploadSettings.get(upload_max_size[action], 0)))
+    if max_size != 0:
+        from .utils import FileSize
+        MF = FileSize(max_size)
+        if upload_file_size > MF.size:
+            state = u"上传文件大小不允许超过%s。" % MF.FriendValue
+
+    # 检测保存路径是否存在,如果不存在则需要创建
+    upload_path_format = {
+        "uploadfile": "filePathFormat",
+        "uploadimage": "imagePathFormat",
+        "uploadscrawl": "scrawlPathFormat",
+        "uploadvideo": "videoPathFormat"
     }
 
-    path_format_var=get_path_format_vars()
+    path_format_var = get_path_format_vars()
     path_format_var.update({
-        "basename":upload_original_name,
-        "extname":upload_original_ext[1:],
-        "filename":upload_file_name,
+        "basename": upload_original_name,
+        "extname": upload_original_ext[1:],
+        "filename": upload_file_name,
     })
-    #取得输出文件的路径
-    OutputPathFormat,OutputPath,OutputFile=get_output_path(request,upload_path_format[action],path_format_var)
-
-    #所有检测完成后写入文件
-    if state=="SUCCESS":
-        if action=="uploadscrawl":
-            state=save_scrawl_file(request, os.path.join(OutputPath,OutputFile))
+    # 取得输出文件的路径
+    OutputPathFormat, OutputPath, OutputFile = get_output_path(
+        request, upload_path_format[action], path_format_var)
+
+    # 所有检测完成后写入文件
+    if state == "SUCCESS":
+        if action == "uploadscrawl":
+            state = save_scrawl_file(
+                request, os.path.join(OutputPath, OutputFile))
         else:
-            #保存到文件中,如果保存错误,需要返回ERROR
-            upload_module_name = USettings.UEditorUploadSettings.get("upload_module", None)
+            # 保存到文件中,如果保存错误,需要返回ERROR
+            upload_module_name = USettings.UEditorUploadSettings.get(
+                "upload_module", None)
             if upload_module_name:
                 mod = import_module(upload_module_name)
                 state = mod.upload(file, OutputPathFormat)
             else:
-                state = save_upload_file(file, os.path.join(OutputPath, OutputFile))
+                state = save_upload_file(
+                    file, os.path.join(OutputPath, OutputFile))
 
-    #返回数据
+    # 返回数据
     return_info = {
-        'url': urllib.basejoin(USettings.gSettings.MEDIA_URL , OutputPathFormat) ,                # 保存后的文件名称
-        'original': upload_file_name,                  #原始文件名
+        # 保存后的文件名称
+        'url': urllib.basejoin(USettings.gSettings.MEDIA_URL, OutputPathFormat),
+        'original': upload_file_name,  # 原始文件名
         'type': upload_original_ext,
-        'state': state,                         #上传状态,成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
+        'state': state,  # 上传状态,成功时返回SUCCESS,其他任何值将原样返回至图片上传框中
         'size': upload_file_size
     }
-    return HttpResponse(json.dumps(return_info,ensure_ascii=False),content_type="application/javascript")
+    return HttpResponse(json.dumps(return_info, ensure_ascii=False), content_type="application/javascript")
+
 
 @csrf_exempt
 def catcher_remote_image(request):
     """远程抓图,当catchRemoteImageEnable:true时,
         如果前端插入图片地址与当前web不在同一个域,则由本函数从远程下载图片到本地
     """
-    if not request.method=="POST":
-        return  HttpResponse(json.dumps( u"{'state:'ERROR'}"),content_type="application/javascript")
+    if not request.method == "POST":
+        return HttpResponse(json.dumps(u"{'state:'ERROR'}"), content_type="application/javascript")
 
-    state="SUCCESS"
+    state = "SUCCESS"
 
-    allow_type= list(request.GET.get("catcherAllowFiles",USettings.UEditorUploadSettings.get("catcherAllowFiles","")))
-    max_size=long(request.GET.get("catcherMaxSize",USettings.UEditorUploadSettings.get("catcherMaxSize",0)))
+    allow_type = list(request.GET.get(
+        "catcherAllowFiles", USettings.UEditorUploadSettings.get("catcherAllowFiles", "")))
+    max_size = long(request.GET.get(
+        "catcherMaxSize", USettings.UEditorUploadSettings.get("catcherMaxSize", 0)))
 
-    remote_urls=request.POST.getlist("source[]",[])
-    catcher_infos=[]
-    path_format_var=get_path_format_vars()
+    remote_urls = request.POST.getlist("source[]", [])
+    catcher_infos = []
+    path_format_var = get_path_format_vars()
 
     for remote_url in remote_urls:
-        #取得上传的文件的原始名称
-        remote_file_name=os.path.basename(remote_url)
-        remote_original_name,remote_original_ext=os.path.splitext(remote_file_name)
-        #文件类型检验
-        if remote_original_ext  in allow_type:
+        # 取得上传的文件的原始名称
+        remote_file_name = os.path.basename(remote_url)
+        remote_original_name, remote_original_ext = os.path.splitext(
+            remote_file_name)
+        # 文件类型检验
+        if remote_original_ext in allow_type:
             path_format_var.update({
-                "basename":remote_original_name,
-                "extname":remote_original_ext[1:],
-                "filename":remote_original_name
+                "basename": remote_original_name,
+                "extname": remote_original_ext[1:],
+                "filename": remote_original_name
             })
-            #计算保存的文件名
-            o_path_format,o_path,o_file=get_output_path(request,"catcherPathFormat",path_format_var)
-            o_filename=os.path.join(o_path,o_file).replace("\\","/")
-            #读取远程图片文件
+            # 计算保存的文件名
+            o_path_format, o_path, o_file = get_output_path(
+                request, "catcherPathFormat", path_format_var)
+            o_filename = os.path.join(o_path, o_file).replace("\\", "/")
+            # 读取远程图片文件
             try:
-                remote_image=urllib.urlopen(remote_url)
-                 #将抓取到的文件写入文件
+                remote_image = urllib.urlopen(remote_url)
+                # 将抓取到的文件写入文件
                 try:
                     f = open(o_filename, 'wb')
                     f.write(remote_image.read())
                     f.close()
-                    state="SUCCESS"
+                    state = "SUCCESS"
                 except Exception as E:
-                    state=u"写入抓取图片文件错误:%s" % E.message
+                    state = u"写入抓取图片文件错误:%s" % E.message
             except Exception as E:
-                state=u"抓取图片错误:%s" % E.message
+                state = u"抓取图片错误:%s" % E.message
 
             catcher_infos.append({
-                "state":state,
-                "url":urllib.basejoin(USettings.gSettings.MEDIA_URL , o_path_format),
-                "size":os.path.getsize(o_filename),
-                "title":os.path.basename(o_file),
-                "original":remote_file_name,
-                "source":remote_url
+                "state": state,
+                "url": urllib.basejoin(USettings.gSettings.MEDIA_URL, o_path_format),
+                "size": os.path.getsize(o_filename),
+                "title": os.path.basename(o_file),
+                "original": remote_file_name,
+                "source": remote_url
             })
 
-    return_info={
-        "state":"SUCCESS" if len(catcher_infos) >0 else "ERROR",
-        "list":catcher_infos
+    return_info = {
+        "state": "SUCCESS" if len(catcher_infos) > 0 else "ERROR",
+        "list": catcher_infos
     }
 
-    return HttpResponse(json.dumps(return_info,ensure_ascii=False),content_type="application/javascript")
-
-
-def get_output_path(request,path_format,path_format_var):
-    #取得输出文件的路径
-    OutputPathFormat=(request.GET.get(path_format,USettings.UEditorSettings["defaultPathFormat"]) % path_format_var).replace("\\","/")
-    #分解OutputPathFormat
-    OutputPath,OutputFile=os.path.split(OutputPathFormat)
-    OutputPath=os.path.join(USettings.gSettings.MEDIA_ROOT,OutputPath)
-    if not OutputFile:#如果OutputFile为空说明传入的OutputPathFormat没有包含文件名,因此需要用默认的文件名
-        OutputFile=USettings.UEditorSettings["defaultPathFormat"] % path_format_var
-        OutputPathFormat=os.path.join(OutputPathFormat,OutputFile)
+    return HttpResponse(json.dumps(return_info, ensure_ascii=False), content_type="application/javascript")
+
+
+def get_output_path(request, path_format, path_format_var):
+    # 取得输出文件的路径
+    OutputPathFormat = (request.GET.get(path_format, USettings.UEditorSettings[
+                        "defaultPathFormat"]) % path_format_var).replace("\\", "/")
+    # 分解OutputPathFormat
+    OutputPath, OutputFile = os.path.split(OutputPathFormat)
+    OutputPath = os.path.join(USettings.gSettings.MEDIA_ROOT, OutputPath)
+    # 如果OutputFile为空说明传入的OutputPathFormat没有包含文件名,因此需要用默认的文件名
+    if not OutputFile:
+        OutputFile = USettings.UEditorSettings[
+            "defaultPathFormat"] % path_format_var
+        OutputPathFormat = os.path.join(OutputPathFormat, OutputFile)
     if not os.path.exists(OutputPath):
         os.makedirs(OutputPath)
-    return ( OutputPathFormat,OutputPath,OutputFile)
+    return (OutputPathFormat, OutputPath, OutputFile)
+
+# 涂鸦功能上传处理
+
 
-#涂鸦功能上传处理
 @csrf_exempt
-def save_scrawl_file(request,filename):
+def save_scrawl_file(request, filename):
     import base64
     try:
-        content=request.POST.get(USettings.UEditorUploadSettings.get("scrawlFieldName","upfile"))
+        content = request.POST.get(
+            USettings.UEditorUploadSettings.get("scrawlFieldName", "upfile"))
         f = open(filename, 'wb')
         f.write(base64.decodestring(content))
         f.close()
-        state="SUCCESS"
+        state = "SUCCESS"
     except Exception as E:
-        state="写入图片文件错误:%s" % E.message
+        state = "写入图片文件错误:%s" % E.message
     return state
-
-

+ 97 - 73
DjangoUeditor/widgets.py

@@ -5,11 +5,14 @@ from django.contrib.admin.widgets import AdminTextareaWidget
 from django.template.loader import render_to_string
 from django.utils.safestring import mark_safe
 from django.utils.http import urlencode
-import DjangoUeditor.settings as USettings
-from  .commands import *
+from . import settings as USettings
+from .commands import *
+from django.utils.six import string_types
 
 # 修正输入的文件路径,输入路径的标准格式:abc,不需要前后置的路径符号
-#如果输入的路径参数是一个函数则执行,否则可以拉接受时间格式化,用来生成如file20121208.bmp的重命名格式
+# 如果输入的路径参数是一个函数则执行,否则可以拉接受时间格式化,用来生成如file20121208.bmp的重命名格式
+
+
 def calc_path(OutputPath, instance=None):
     if callable(OutputPath):
         try:
@@ -25,46 +28,50 @@ def calc_path(OutputPath, instance=None):
 
     return OutputPath
 
-#width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={},
-                # settings={},command=None,event_handler=None
+# width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={},
+    # settings={},command=None,event_handler=None
+
+
 class UEditorWidget(forms.Textarea):
-    def __init__(self,attrs=None):
-
-        params=attrs.copy()
-
-        width=params.pop("width")
-        height=params.pop("height")
-        toolbars=params.pop("toolbars","full")
-        imagePath=params.pop("imagePath","")
-        filePath=params.pop("filePath","")
-        upload_settings=params.pop("upload_settings",{})
-        settings=params.pop("settings",{})
-        command=params.pop("command",None)
-        event_handler=params.pop("event_handler",None)
-
-        #扩展命令
-        self.command=command
-        self.event_handler=event_handler
-        #上传路径
+
+    def __init__(self, attrs=None):
+
+        params = attrs.copy()
+
+        width = params.pop("width")
+        height = params.pop("height")
+        toolbars = params.pop("toolbars", "full")
+        imagePath = params.pop("imagePath", "")
+        filePath = params.pop("filePath", "")
+        upload_settings = params.pop("upload_settings", {})
+        settings = params.pop("settings", {})
+        command = params.pop("command", None)
+        event_handler = params.pop("event_handler", None)
+
+        # 扩展命令
+        self.command = command
+        self.event_handler = event_handler
+        # 上传路径
         self.upload_settings = upload_settings.copy()
         self.upload_settings.update({
             "imagePathFormat": imagePath,
             "filePathFormat": filePath
         })
-        #保存
-        self._upload_settings =self.upload_settings.copy()
+        # 保存
+        self._upload_settings = self.upload_settings.copy()
         self.recalc_path(None)
 
-        self.ueditor_settings ={
-            'toolbars':toolbars,
-            'initialFrameWidth':width,
-            'initialFrameHeight':height
+        self.ueditor_settings = {
+            'toolbars': toolbars,
+            'initialFrameWidth': width,
+            'initialFrameHeight': height
         }
-        #以下处理工具栏设置,将normal,mini等模式名称转化为工具栏配置值
+        # 以下处理工具栏设置,将normal,mini等模式名称转化为工具栏配置值
         if toolbars == "full":
             del self.ueditor_settings['toolbars']
-        elif isinstance(toolbars, str) and toolbars in USettings.TOOLBARS_SETTINGS:
-            self.ueditor_settings["toolbars"]=USettings.TOOLBARS_SETTINGS[toolbars]
+        elif isinstance(toolbars, string_types) and toolbars in USettings.TOOLBARS_SETTINGS:
+            self.ueditor_settings[
+                "toolbars"] = USettings.TOOLBARS_SETTINGS[toolbars]
         else:
             self.ueditor_settings["toolbars"] = toolbars
             # raise ValueError('toolbars should be a string defined in DjangoUeditor.settings.TOOLBARS_SETTINGS, options are full(default), besttome, mini and normal!')
@@ -75,61 +82,77 @@ class UEditorWidget(forms.Textarea):
         """计算上传路径,允许是function"""
         try:
             uSettings = self.upload_settings
-            if self._upload_settings.has_key("filePathFormat"):
-                uSettings['filePathFormat'] = calc_path(self._upload_settings['filePathFormat'], model_inst)
-            if self._upload_settings.has_key("imagePathFormat"):
-                uSettings['imagePathFormat'] = calc_path(self._upload_settings['imagePathFormat'], model_inst)
-            if self._upload_settings.has_key("scrawlPathFormat"):
-                uSettings['scrawlPathFormat'] = calc_path(self._upload_settings['scrawlPathFormat'], model_inst)
-            if self._upload_settings.has_key("videoPathFormat"):
-                uSettings['videoPathFormat'] = calc_path(self._upload_settings['videoPathFormat'], model_inst),
-            if self._upload_settings.has_key("snapscreenPathFormat"):
-                uSettings['snapscreenPathFormat'] = calc_path(self._upload_settings['snapscreenPathFormat'], model_inst)
-            if self._upload_settings.has_key("catcherPathFormat"):
-                uSettings['catcherPathFormat'] = calc_path(self._upload_settings['catcherPathFormat'], model_inst)
-            if self._upload_settings.has_key("imageManagerListPath"):
-                uSettings['imageManagerListPath'] = calc_path(self._upload_settings['imageManagerListPath'], model_inst)
-            if self._upload_settings.has_key("fileManagerListPath"):
-                uSettings['fileManagerListPath'] = calc_path(self._upload_settings['fileManagerListPath'], model_inst)
-            #设置默认值,未指定涂鸦、截图、远程抓图、图片目录时,默认均等于imagePath
-            if uSettings['imagePathFormat']!="":
-                uSettings['scrawlPathFormat']=uSettings['scrawlPathFormat'] if self._upload_settings.has_key("scrawlPathFormat") else uSettings['imagePathFormat']
-                uSettings['videoPathFormat']=uSettings['videoPathFormat'] if self._upload_settings.has_key("videoPathFormat") else uSettings['imagePathFormat']
-                uSettings['snapscreenPathFormat']=uSettings['snapscreenPathFormat'] if self._upload_settings.has_key("snapscreenPathFormat") else uSettings['imagePathFormat']
-                uSettings['catcherPathFormat']=uSettings['catcherPathFormat'] if self._upload_settings.has_key("catcherPathFormat") else uSettings['imagePathFormat']
-                uSettings['imageManagerListPath']=uSettings['imageManagerListPath'] if self._upload_settings.has_key("imageManagerListPath") else uSettings['imagePathFormat']
-            if uSettings['filePathFormat']!="":
-                uSettings['fileManagerListPath']=uSettings['fileManagerListPath'] if self._upload_settings.has_key("fileManagerListPath") else uSettings['filePathFormat']
+            if 'filePathFormat' in self._upload_settings:
+                uSettings['filePathFormat'] = calc_path(
+                    self._upload_settings['filePathFormat'], model_inst)
+            if 'imagePathFormat' in self._upload_settings:
+                uSettings['imagePathFormat'] = calc_path(
+                    self._upload_settings['imagePathFormat'], model_inst)
+            if 'scrawlPathFormat' in self._upload_settings:
+                uSettings['scrawlPathFormat'] = calc_path(
+                    self._upload_settings['scrawlPathFormat'], model_inst)
+            if 'videoPathFormat' in self._upload_settings:
+                uSettings['videoPathFormat'] = calc_path(
+                    self._upload_settings['videoPathFormat'], model_inst),
+            if 'snapscreenPathFormat' in self._upload_settings:
+                uSettings['snapscreenPathFormat'] = calc_path(
+                    self._upload_settings['snapscreenPathFormat'], model_inst)
+            if 'catcherPathFormat' in self._upload_settings:
+                uSettings['catcherPathFormat'] = calc_path(
+                    self._upload_settings['catcherPathFormat'], model_inst)
+            if 'imageManagerListPath' in self._upload_settings:
+                uSettings['imageManagerListPath'] = calc_path(
+                    self._upload_settings['imageManagerListPath'], model_inst)
+            if 'fileManagerListPath' in self._upload_settings:
+                uSettings['fileManagerListPath'] = calc_path(
+                    self._upload_settings['fileManagerListPath'], model_inst)
+            # 设置默认值,未指定涂鸦、截图、远程抓图、图片目录时,默认均等于imagePath
+            if uSettings['imagePathFormat'] != "":
+                default_path = uSettings['imagePathFormat']
+
+                uSettings['scrawlPathFormat'] = uSettings.get(
+                    'scrawlPathFormat', default_path)
+                uSettings['videoPathFormat'] = uSettings.get(
+                    'videoPathFormat', default_path)
+                uSettings['snapscreenPathFormat'] = uSettings.get(
+                    'snapscreenPathFormat', default_path)
+                uSettings['catcherPathFormat'] = uSettings.get(
+                    'catcherPathFormat', default_path)
+                uSettings['imageManagerListPath'] = uSettings.get(
+                    'imageManagerListPath', default_path)
+
+            if uSettings['filePathFormat'] != "":
+                uSettings['fileManagerListPath'] = uSettings.get(
+                    'fileManagerListPath', uSettings['filePathFormat'])
         except:
             pass
 
-
     def render(self, name, value, attrs=None):
-        if value is None: value = ''
-        #传入模板的参数
-        editor_id="id_%s" % name.replace("-", "_")
-        uSettings={
+        if value is None:
+            value = ''
+        # 传入模板的参数
+        editor_id = "id_%s" % name.replace("-", "_")
+        uSettings = {
             "name": name,
             "id": editor_id,
-            "value":value
+            "value": value
         }
-        if isinstance(self.command,list):
-            cmdjs=""
-            if isinstance(self.command,list):
+        if isinstance(self.command, list):
+            cmdjs = ""
+            if isinstance(self.command, list):
                 for cmd in self.command:
-                    cmdjs=cmdjs+cmd.render(editor_id)
+                    cmdjs = cmdjs + cmd.render(editor_id)
             else:
-                cmdis=self.command.render(editor_id)
-            uSettings["commands"]=cmdjs
-
+                cmdjs = self.command.render(editor_id)
+            uSettings["commands"] = cmdjs
 
         uSettings["settings"] = self.ueditor_settings.copy()
         uSettings["settings"].update({
             "serverUrl": "/ueditor/controller/?%s" % urlencode(self._upload_settings)
         })
-        #生成事件侦听
+        # 生成事件侦听
         if self.event_handler:
-            uSettings["bindEvents"]=self.event_handler.render(editor_id)
+            uSettings["bindEvents"] = self.event_handler.render(editor_id)
 
         context = {
             'UEditor': uSettings,
@@ -145,6 +168,7 @@ class UEditorWidget(forms.Textarea):
               "ueditor/ueditor.all.min.js")
 
 
-class AdminUEditorWidget(AdminTextareaWidget,UEditorWidget ):
+class AdminUEditorWidget(AdminTextareaWidget, UEditorWidget):
+
     def __init__(self, **kwargs):
         super(AdminUEditorWidget, self).__init__(**kwargs)