widgets.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.html import conditional_escape
  8. from django.utils.encoding import force_unicode
  9. import json
  10. from utils import MadeUeditorOptions
  11. import settings as USettings
  12. class UEditorWidget(forms.Textarea):
  13. def __init__(self,width=600,height=300,plugins=(),toolbars="normal",filePath="",imagePath="",scrawlPath="",imageManagerPath="",css="",sourceEditorFirst=False,options={}, attrs=None,**kwargs):
  14. self.ueditor_options=MadeUeditorOptions(width,height,plugins,toolbars,filePath,imagePath,scrawlPath,imageManagerPath,css,sourceEditorFirst,options)
  15. super(UEditorWidget, self).__init__(attrs)
  16. def render(self, name, value, attrs=None):
  17. if value is None: value = ''
  18. #取得工具栏设置
  19. try:
  20. if type(self.ueditor_options['toolbars'])==list:
  21. tbar=json.dumps(self.ueditor_options['toolbars'])
  22. else:
  23. if getattr(USettings,"TOOLBARS_SETTINGS",{}).has_key(str(self.ueditor_options['toolbars'])):
  24. if self.ueditor_options['toolbars'] =="full":
  25. tbar=None
  26. else:
  27. tb=USettings.TOOLBARS_SETTINGS[str(self.ueditor_options['toolbars'])]
  28. tbar=json.dumps(tb)
  29. else:
  30. tbar=None
  31. except:
  32. pass
  33. #传入模板的参数
  34. uOptions=self.ueditor_options.copy()
  35. uOptions.update({
  36. "name":name,
  37. "value":conditional_escape(force_unicode(value)),
  38. "toolbars":tbar,
  39. "options":json.dumps(self.ueditor_options['options'])[1:-1]
  40. #str(self.ueditor_options['options'])[1:-1].replace("True","true").replace("False","false").replace("'",'"')
  41. })
  42. context = {
  43. 'UEditor':uOptions,
  44. 'STATIC_URL':settings.STATIC_URL,
  45. 'STATIC_ROOT':settings.STATIC_ROOT,
  46. 'MEDIA_URL':settings.MEDIA_URL,
  47. 'MEDIA_ROOT':settings.MEDIA_ROOT
  48. }
  49. return mark_safe(render_to_string('ueditor.html',context))
  50. class Media:
  51. css={"all": ("ueditor/themes/default/css/ueditor.css" ,
  52. "ueditor/themes/iframe.css" ,
  53. )}
  54. js=("ueditor/ueditor.config.js",
  55. "ueditor/ueditor.all.min.js")
  56. class AdminUEditorWidget(AdminTextareaWidget, UEditorWidget):
  57. def __init__(self,**kwargs):
  58. self.ueditor_options=kwargs
  59. super(UEditorWidget,self).__init__(kwargs)