您的位置:首页 > 编程语言 > Go语言

如何把nicEditor集成到django中使用

2014-10-29 15:05 417 查看
http://blog.csdn.net/huyoo/article/details/4382317

我在我的ddtcms将会采用nicEditor作为表单中texteare的rich text editor

首先要,下载并解压nicEditor到media目录,我在media目录下建立了一个叫做editor的目录,下面放nicEditor或者tinymce之类的html编辑器

这里主要是介绍方法 

然后就是建立一个NicEditor类,继承于Textarea(forms.Textarea),代码如下:

[python] view
plaincopy

class NicEditor(Textarea):  

  

    class Media:  

        js = ("%seditor/nicEdit/nicEdit.js" % settings.MEDIA_URL,)  

  

    def __init__(self,  attrs=None):  

        self.attrs = {'class': 'niceditor'}  

        if attrs:  

            self.attrs.update(attrs)  

        super(NicEditor, self).__init__(attrs)  

  

    def render(self, name, value, attrs=None):  

        rendered = super(NicEditor, self).render(name, value, attrs)  

        context = {  

            'name': name,  

            'MEDIA_URL':settings.MEDIA_URL,  

        }  

        return rendered  + mark_safe(render_to_string(  

            '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吧.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: