如何把nicEditor集成到django中使用

我在我的ddtcms将会采用nicEditor作为表单中texteare的rich text editor
首先要,下载并解压nicEditor到media目录,我在media目录下建立了一个叫做editor的目录,下面放nicEditor或者tinymce之类的html编辑器

这里主要是介绍方法
然后就是建立一个NicEditor类,继承于Textarea(forms.Textarea),代码如下:

[python] view plain copy
  1. class NicEditor(Textarea):  
  2.   
  3.     class Media:  
  4.         js = ("%seditor/nicEdit/nicEdit.js" % settings.MEDIA_URL,)  
  5.   
  6.     def __init__(self,  attrs=None):  
  7.         self.attrs = {'class''niceditor'}  
  8.         if attrs:  
  9.             self.attrs.update(attrs)  
  10.         super(NicEditor, self).__init__(attrs)  
  11.   
  12.     def render(self, name, value, attrs=None):  
  13.         rendered = super(NicEditor, self).render(name, value, attrs)  
  14.         context = {  
  15.             'name': name,  
  16.             'MEDIA_URL':settings.MEDIA_URL,  
  17.         }  
  18.         return rendered  + mark_safe(render_to_string(  
  19.             'niceditor/niceditor.html', context))   

然后在你的某个app的forms.py 中使用它:
class CreateNewsForm(forms.Form):
    title = forms.CharField(label=_("Title"),  widget=forms.TextInput(attrs={'size': 50,'class': 'required'}), max_length=100,help_text="max_length is 100")
    body = forms.CharField(label=_("Body"), widget=NicEditor(attrs={'rows':8, 'cols':50})) 

可以看出,上面就是定义了一个widget(NicEditor),这个widget使用的是渲染模板弄的,模板文件是:niceditor/niceditor.html,内容如下:
<script type="text/javascript" src="{{MEDIA_URL}}editor/nicEdit/nicEdit.js"></script>
<script type="text/javascript">bkLib.onDomLoaded(function(){new nicEditor({maxHeight : 200}).panelInstance('id_{{name}}');});</script>

这上面的一段就是说把form中的一个name为id_body 的textare采用js处理后成为一个nicEditor

其他的forms.py中要使用nicEditor的地方都是按照上面说的弄

niceditor/niceditor.html可以放到templates目录下

可能需要应用的库是:
from django import forms
from django.utils.translation import ugettext as _
from django.forms import TextInput, Textarea
from django.conf import settings
from django.utils.safestring import mark_safe
from django.template import RequestContext
from django.template.loader import render_to_string

可以使用继承forms.Textarea的方法定义其他的editor,怎么渲染它就是你自己的事情了。对于一个基于jquery的editor:wymeditor来说,也可以使用同样的方法
上面的niceditor的一个背景图片要注意修改成正确的路径,可以修改niceditor的源码解决。

好了,就这些了,以后把代码发到google code吧.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值