django 整合 kindeditor
1 修改:
Djangosettings.py
STATICFILES_DIRS=(
("css",os.path.join(PROJECT_PATH,'static/css')),
("img",os.path.join(PROJECT_PATH,'static/img')),
("js",os.path.join(PROJECT_PATH,'static/js')),
("editor",os.path.join(PROJECT_PATH,'static/editor')),
)
2下载kindeditor,然后把文件放进/static/里。如下:
ubuntu@yee:~/ndis/static$tree-L2
.
├──css
│└──style.css
├──editor
│└──kindeditor#把下载的kindeditor放进去。
├──img
└──jsubuntu@yee:~/ndis/static/editor/kindeditor$ls
kindeditor-all.jskindeditor.jslangthemes
kindeditor-all-min.jskindeditor-min.jsplugins3在项目目录下创建rte
ubuntu@yee:~/ndis/rte$tree
.
├──__init__.py
├──__init__.pyc
├──kindeditor
│├──__init__.py
│├──__init__.pyc
│├──widgets.py
│└──widgets.pyc
├──models.py
├──tests.py
└──views.py4编写rte/kindeditor/widgets.py
fromdjangoimportforms
fromdjango.confimportsettings
fromdjango.utils.safestringimportmark_safe
fromdjango.template.loaderimportrender_to_string
fromdjango.templateimportRequestContext
fromdjango.utils.translationimportugettext_lazyas_
classKindEditor(forms.Textarea):
classMedia:
css={
'all':(settings.STATIC_URL+'editor/kindeditor/themes/default/default.css',
settings.STATIC_URL+'editor/kindeditor/plugins/code/prettify.js',),
}
js=(
"%seditor/kindeditor/kindeditor.js"%settings.STATIC_URL,
settings.STATIC_URL+'editor/kindeditor/plugins/code/prettify.js',
)
def__init__(self,attrs={}):
#attrs['style']="width:800px;height:400px;visibility:hidden;"
super(KindEditor,self).__init__(attrs)
defrender(self,name,value,attrs=None):
rendered=super(KindEditor,self).render(name,value,attrs)
context={
'name':name,
'STATIC_URL':settings.STATIC_URL,
}
returnrendered+mark_safe(render_to_string('editor/kindeditor.html',context))5editor/kindeditor.html
<scripttype="text/javascript">
vareditor;//定义为全局变量,这点很重要
KindEditor.ready(function(K){
varoptions={
cssPath:('{{STATIC_URL}}editor/kindeditor/themes/default/default.css',
'{{STATIC_URL}}editor/kindeditor/plugins/code/prettify.css'),
width:'680px',
height:'400px',
filterMode:true
};
editor=K.create('textarea[name="content"]',options);
});
</script>
6forms.py
fromrte.kindeditor.widgetsimportKindEditor
content=forms.CharField(widget=KindEditor(attrs={'rows':15,'cols':100}))7引入js文件
<scriptcharset="utf-8"src="{{STATIC_URL}}editor/kindeditor/kindeditor.js"></script>如果你用的是ajax来提交数据,要如下:
$("#post_answer_form").submit(function(){
editor.sync();//仔细看kindeditor文档,上面说明了默认在遇到onsubmit事件时,会将iframe中的数据传输到你的textarea中,所以我们想要获取数据之前,最好是手工同步一下。我就遇到这个问题,需要提交两次才能拿到数据。
var data = $(this).serialize();