Django輕鬆使用富文本編輯器-KindEditorjavascript
因爲須要在django admin中使用到富文本編輯器,因爲我比較喜歡KindEditor,因而寫了個自定義widget
一、首先從KindEditor主頁下載,並解壓至你的static文件存放目錄(略...)
二、編寫自定義widget:css
from django import forms
html
from django.conf import settings
java
class KindEditor(forms.Textarea):
django
class Media:
app
js = (settings.MEDIA_URL + 'js/widgets/kindeditor.js',)
編輯器
css = (settings.MEDIA_URL + 'js/widgets/kindeditor.css',)
this
def __init__(self, attrs = {}):
spa
attrs['rel'] = 'kind'
orm
super(KindEditor, self).__init__(attrs)
複製代碼
三、在form中使用上面的widget:
from customwidget.editor import KindEditor
from django import forms
from app.models import MyModel
from django.contrib import admin
class MyModelAdminForm(forms.ModelForm):
pass
class Meta:
model = MyModel
widgets = {
'fieldname':KindEditor()
}
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
admin.site.register(MyModel, MyModelAdmin)
複製代碼
四、須要在模板中使用JS來初始化KindEditor(請確保你的模板中已加載jQuery, django admin中已自帶,不過namespace換到了django之下):
{%extends "admin/change_form.html"%}
{%block extrahead%}
{{block.super}}
<script type="text/javascript">
django.jQuery(document).ready(function(){
django.jQuery("textarea[rel='kind']").each(function(n){
KE.show({
id : django.jQuery(this).attr("id"),
});
});
});
</script>
{%endblock%}
複製代碼
四、須要注意的地方:
a) 所下載的kindeditor文件包存放的位置及settings裏的MEDIA_URL地址(其實就是保證最終生成的JS和CSS訪問路徑是正確的)
b) 若非django admin的模板,請自行加載jQuery