django 整合 kindeditor
参考这篇文章。http://blog.csdn.net/huyoo/article/details/6913973
我的环境是django 1.3
1
Django settings.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 -L 2 . ├── css │ └── style.css ├── editor │ └── kindeditor #把下载的kindeditor放进去。 ├── img └── js
ubuntu@yee:~/ndis/static/editor/kindeditor$ ls kindeditor-all.js kindeditor.js lang themes kindeditor-all-min.js kindeditor-min.js plugins
3 在项目目录下创建 rte
ubuntu@yee:~/ndis/rte$ tree
.
├── __init__.py
├── __init__.pyc
├── kindeditor
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── widgets.py
│ └── widgets.pyc
├── models.py
├── tests.py
└── views.py
4 编写 rte/kindeditor/widgets.py
from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.template.loader import render_to_string from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ class KindEditor(forms.Textarea): class Media: 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) def render(self, name, value, attrs=None): rendered = super(KindEditor, self).render(name, value, attrs) context = { 'name': name, 'STATIC_URL':settings.STATIC_URL, } return rendered + mark_safe(render_to_string('editor/kindeditor.html', context))
5 editor/kindeditor.html
<script type="text/javascript"> var editor ; //定义为全局变量,这点很重要 KindEditor.ready(function(K) { var options = { 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>
6 forms.py
from rte.kindeditor.widgets import KindEditor content = forms.CharField( widget=KindEditor(attrs={'rows':15, 'cols':100}))
7 引入 js 文件
<script charset="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();
www.notewo.com