widgets.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # coding:utf-8
  2. from django import forms
  3. from django.conf import settings
  4. from django.contrib.admin.widgets import AdminTextareaWidget
  5. from django.template.loader import render_to_string
  6. from django.utils.safestring import mark_safe
  7. from django.utils.http import urlencode
  8. import settings as USettings
  9. from commands import *
  10. # 修正输入的文件路径,输入路径的标准格式:abc,不需要前后置的路径符号
  11. #如果输入的路径参数是一个函数则执行,否则可以拉接受时间格式化,用来生成如file20121208.bmp的重命名格式
  12. def calc_path(OutputPath, instance=None):
  13. if callable(OutputPath):
  14. try:
  15. OutputPath = OutputPath(instance)
  16. except:
  17. OutputPath = ""
  18. else:
  19. try:
  20. import datetime
  21. OutputPath = datetime.datetime.now().strftime(OutputPath)
  22. except:
  23. pass
  24. return OutputPath
  25. #width=600, height=300, toolbars="full", imagePath="", filePath="", upload_settings={},
  26. # settings={},command=None,event_handler=None
  27. class UEditorWidget(forms.Textarea):
  28. def __init__(self,attrs=None):
  29. params=attrs.copy()
  30. width=params.pop("width")
  31. height=params.pop("height")
  32. toolbars=params.pop("toolbars","full")
  33. imagePath=params.pop("imagePath","")
  34. filePath=params.pop("filePath","")
  35. upload_settings=params.pop("upload_settings",{})
  36. settings=params.pop("settings",{})
  37. command=params.pop("command",None)
  38. event_handler=params.pop("event_handler",None)
  39. #扩展命令
  40. self.command=command
  41. self.event_handler=event_handler
  42. #上传路径
  43. self.upload_settings = upload_settings.copy()
  44. self.upload_settings.update({
  45. "imagePathFormat": imagePath,
  46. "filePathFormat": filePath
  47. })
  48. #保存
  49. self._upload_settings =self.upload_settings.copy()
  50. self.recalc_path(None)
  51. self.ueditor_settings ={
  52. 'toolbars':toolbars,
  53. 'initialFrameWidth':width,
  54. 'initialFrameHeight':height
  55. }
  56. #以下处理工具栏设置,将normal,mini等模式名称转化为工具栏配置值
  57. if toolbars == "full":
  58. del self.ueditor_settings['toolbars']
  59. elif isinstance(toolbars, basestring) and toolbars in USettings.TOOLBARS_SETTINGS:
  60. self.ueditor_settings["toolbars"]=USettings.TOOLBARS_SETTINGS[toolbars]
  61. else:
  62. raise ValueError('toolbars should be a string defined in DjangoUeditor.settings.TOOLBARS_SETTINGS, options are full(default), besttome, mini and normal!')
  63. self.ueditor_settings.update(settings)
  64. super(UEditorWidget, self).__init__(attrs)
  65. def recalc_path(self, model_inst):
  66. """计算上传路径,允许是function"""
  67. try:
  68. uSettings = self.upload_settings
  69. if self._upload_settings.has_key("filePathFormat"):
  70. uSettings['filePathFormat'] = calc_path(self._upload_settings['filePathFormat'], model_inst)
  71. if self._upload_settings.has_key("imagePathFormat"):
  72. uSettings['imagePathFormat'] = calc_path(self._upload_settings['imagePathFormat'], model_inst)
  73. if self._upload_settings.has_key("scrawlPathFormat"):
  74. uSettings['scrawlPathFormat'] = calc_path(self._upload_settings['scrawlPathFormat'], model_inst)
  75. if self._upload_settings.has_key("videoPathFormat"):
  76. uSettings['videoPathFormat'] = calc_path(self._upload_settings['videoPathFormat'], model_inst),
  77. if self._upload_settings.has_key("snapscreenPathFormat"):
  78. uSettings['snapscreenPathFormat'] = calc_path(self._upload_settings['snapscreenPathFormat'], model_inst)
  79. if self._upload_settings.has_key("catcherPathFormat"):
  80. uSettings['catcherPathFormat'] = calc_path(self._upload_settings['catcherPathFormat'], model_inst)
  81. if self._upload_settings.has_key("imageManagerListPath"):
  82. uSettings['imageManagerListPath'] = calc_path(self._upload_settings['imageManagerListPath'], model_inst)
  83. if self._upload_settings.has_key("fileManagerListPath"):
  84. uSettings['fileManagerListPath'] = calc_path(self._upload_settings['fileManagerListPath'], model_inst)
  85. #设置默认值,未指定涂鸦、截图、远程抓图、图片目录时,默认均等于imagePath
  86. if uSettings['imagePathFormat']!="":
  87. uSettings['scrawlPathFormat']=uSettings['scrawlPathFormat'] if self._upload_settings.has_key("scrawlPathFormat") else uSettings['imagePathFormat']
  88. uSettings['videoPathFormat']=uSettings['videoPathFormat'] if self._upload_settings.has_key("videoPathFormat") else uSettings['imagePathFormat']
  89. uSettings['snapscreenPathFormat']=uSettings['snapscreenPathFormat'] if self._upload_settings.has_key("snapscreenPathFormat") else uSettings['imagePathFormat']
  90. uSettings['catcherPathFormat']=uSettings['catcherPathFormat'] if self._upload_settings.has_key("catcherPathFormat") else uSettings['imagePathFormat']
  91. uSettings['imageManagerListPath']=uSettings['imageManagerListPath'] if self._upload_settings.has_key("imageManagerListPath") else uSettings['imagePathFormat']
  92. if uSettings['filePathFormat']!="":
  93. uSettings['fileManagerListPath']=uSettings['fileManagerListPath'] if self._upload_settings.has_key("fileManagerListPath") else uSettings['filePathFormat']
  94. except:
  95. pass
  96. def render(self, name, value, attrs=None):
  97. if value is None: value = ''
  98. #传入模板的参数
  99. editor_id="id_%s" % name.replace("-", "_")
  100. uSettings={
  101. "name": name,
  102. "id": editor_id,
  103. "value":value
  104. }
  105. if isinstance(self.command,list):
  106. cmdjs=""
  107. if isinstance(self.command,list):
  108. for cmd in self.command:
  109. cmdjs=cmdjs+cmd.render(editor_id)
  110. else:
  111. cmdis=self.command.render(editor_id)
  112. uSettings["commands"]=cmdjs
  113. uSettings["settings"] = self.ueditor_settings.copy()
  114. uSettings["settings"].update({
  115. "serverUrl": "/ueditor/controller/?%s" % urlencode(self._upload_settings)
  116. })
  117. #生成事件侦听
  118. if self.event_handler:
  119. uSettings["bindEvents"]=self.event_handler.render(editor_id)
  120. context = {
  121. 'UEditor': uSettings,
  122. 'STATIC_URL': settings.STATIC_URL,
  123. 'STATIC_ROOT': settings.STATIC_ROOT,
  124. 'MEDIA_URL': settings.MEDIA_URL,
  125. 'MEDIA_ROOT': settings.MEDIA_ROOT
  126. }
  127. return mark_safe(render_to_string('ueditor.html', context))
  128. class Media:
  129. js = ("ueditor/ueditor.config.js",
  130. "ueditor/ueditor.all.min.js")
  131. class AdminUEditorWidget(AdminTextareaWidget,UEditorWidget ):
  132. def __init__(self, **kwargs):
  133. super(AdminUEditorWidget, self).__init__(**kwargs)