widgets.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 DjangoUeditor.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, str) and toolbars in USettings.TOOLBARS_SETTINGS:
  60. self.ueditor_settings["toolbars"]=USettings.TOOLBARS_SETTINGS[toolbars]
  61. else:
  62. self.ueditor_settings["toolbars"] = toolbars
  63. # raise ValueError('toolbars should be a string defined in DjangoUeditor.settings.TOOLBARS_SETTINGS, options are full(default), besttome, mini and normal!')
  64. self.ueditor_settings.update(settings)
  65. super(UEditorWidget, self).__init__(attrs)
  66. def recalc_path(self, model_inst):
  67. """计算上传路径,允许是function"""
  68. try:
  69. uSettings = self.upload_settings
  70. if self._upload_settings.has_key("filePathFormat"):
  71. uSettings['filePathFormat'] = calc_path(self._upload_settings['filePathFormat'], model_inst)
  72. if self._upload_settings.has_key("imagePathFormat"):
  73. uSettings['imagePathFormat'] = calc_path(self._upload_settings['imagePathFormat'], model_inst)
  74. if self._upload_settings.has_key("scrawlPathFormat"):
  75. uSettings['scrawlPathFormat'] = calc_path(self._upload_settings['scrawlPathFormat'], model_inst)
  76. if self._upload_settings.has_key("videoPathFormat"):
  77. uSettings['videoPathFormat'] = calc_path(self._upload_settings['videoPathFormat'], model_inst),
  78. if self._upload_settings.has_key("snapscreenPathFormat"):
  79. uSettings['snapscreenPathFormat'] = calc_path(self._upload_settings['snapscreenPathFormat'], model_inst)
  80. if self._upload_settings.has_key("catcherPathFormat"):
  81. uSettings['catcherPathFormat'] = calc_path(self._upload_settings['catcherPathFormat'], model_inst)
  82. if self._upload_settings.has_key("imageManagerListPath"):
  83. uSettings['imageManagerListPath'] = calc_path(self._upload_settings['imageManagerListPath'], model_inst)
  84. if self._upload_settings.has_key("fileManagerListPath"):
  85. uSettings['fileManagerListPath'] = calc_path(self._upload_settings['fileManagerListPath'], model_inst)
  86. #设置默认值,未指定涂鸦、截图、远程抓图、图片目录时,默认均等于imagePath
  87. if uSettings['imagePathFormat']!="":
  88. uSettings['scrawlPathFormat']=uSettings['scrawlPathFormat'] if self._upload_settings.has_key("scrawlPathFormat") else uSettings['imagePathFormat']
  89. uSettings['videoPathFormat']=uSettings['videoPathFormat'] if self._upload_settings.has_key("videoPathFormat") else uSettings['imagePathFormat']
  90. uSettings['snapscreenPathFormat']=uSettings['snapscreenPathFormat'] if self._upload_settings.has_key("snapscreenPathFormat") else uSettings['imagePathFormat']
  91. uSettings['catcherPathFormat']=uSettings['catcherPathFormat'] if self._upload_settings.has_key("catcherPathFormat") else uSettings['imagePathFormat']
  92. uSettings['imageManagerListPath']=uSettings['imageManagerListPath'] if self._upload_settings.has_key("imageManagerListPath") else uSettings['imagePathFormat']
  93. if uSettings['filePathFormat']!="":
  94. uSettings['fileManagerListPath']=uSettings['fileManagerListPath'] if self._upload_settings.has_key("fileManagerListPath") else uSettings['filePathFormat']
  95. except:
  96. pass
  97. def render(self, name, value, attrs=None):
  98. if value is None: value = ''
  99. #传入模板的参数
  100. editor_id="id_%s" % name.replace("-", "_")
  101. uSettings={
  102. "name": name,
  103. "id": editor_id,
  104. "value":value
  105. }
  106. if isinstance(self.command,list):
  107. cmdjs=""
  108. if isinstance(self.command,list):
  109. for cmd in self.command:
  110. cmdjs=cmdjs+cmd.render(editor_id)
  111. else:
  112. cmdis=self.command.render(editor_id)
  113. uSettings["commands"]=cmdjs
  114. uSettings["settings"] = self.ueditor_settings.copy()
  115. uSettings["settings"].update({
  116. "serverUrl": "/ueditor/controller/?%s" % urlencode(self._upload_settings)
  117. })
  118. #生成事件侦听
  119. if self.event_handler:
  120. uSettings["bindEvents"]=self.event_handler.render(editor_id)
  121. context = {
  122. 'UEditor': uSettings,
  123. 'STATIC_URL': settings.STATIC_URL,
  124. 'STATIC_ROOT': settings.STATIC_ROOT,
  125. 'MEDIA_URL': settings.MEDIA_URL,
  126. 'MEDIA_ROOT': settings.MEDIA_ROOT
  127. }
  128. return mark_safe(render_to_string('ueditor.html', context))
  129. class Media:
  130. js = ("ueditor/ueditor.config.js",
  131. "ueditor/ueditor.all.min.js")
  132. class AdminUEditorWidget(AdminTextareaWidget,UEditorWidget ):
  133. def __init__(self, **kwargs):
  134. super(AdminUEditorWidget, self).__init__(**kwargs)