widgets.py 2.7 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. from django.utils import simplejson
  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="",options={}, attrs=None,**kwargs):
  14. self.ueditor_options=MadeUeditorOptions(width,height,plugins,toolbars,filePath,imagePath,scrawlPath,imageManagerPath,css,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=simplejson.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. tbar=simplejson.dumps(USettings.TOOLBARS_SETTINGS[str(self.ueditor_options['toolbars'])])
  28. else:
  29. tbar=None
  30. except:
  31. pass
  32. #传入模板的参数
  33. uOptions=self.ueditor_options.copy()
  34. uOptions.update({
  35. "name":name,
  36. "value":conditional_escape(force_unicode(value)),
  37. "toolbars":tbar,
  38. "options":simplejson.dumps(self.ueditor_options['options'])[1:-1]
  39. #str(self.ueditor_options['options'])[1:-1].replace("True","true").replace("False","false").replace("'",'"')
  40. })
  41. context = {
  42. 'UEditor':uOptions,
  43. 'STATIC_URL':settings.STATIC_URL,
  44. 'STATIC_ROOT':settings.STATIC_ROOT,
  45. 'MEDIA_URL':settings.MEDIA_URL,
  46. 'MEDIA_ROOT':settings.MEDIA_ROOT
  47. }
  48. return mark_safe(render_to_string('ueditor.html',context))
  49. class Media:
  50. css={"all": ("ueditor/themes/default/ueditor.css" ,
  51. "ueditor/themes/default/iframe.css" ,
  52. )}
  53. js=("ueditor/editor_config.js",
  54. "ueditor/editor_all_min.js")
  55. class AdminUEditorWidget(AdminTextareaWidget, UEditorWidget):
  56. def __init__(self,**kwargs):
  57. self.ueditor_options=kwargs
  58. super(UEditorWidget,self).__init__(kwargs)