一、安裝
- pip命令安裝,由於ueditor為百度開發的一款富文本編輯框,現已停止維護,如果解釋器為python2,則直接
pip install djangoueditor
- 解壓包安裝,python3以上的版本需要下載壓縮包解壓安裝 下載地址
步驟- 到下載地址下載並解壓
- cmd進入該文件夾根目錄
python setup.py install
直接安裝到當前site-package中
二、添加app
將djangoueditor添加到setting.py中
INSTALLED_APPS = [
...
'DjangoUeditor',
]
三、添加url
將URL添加到urlpatterns中去:
富文本編輯器
url(r'^ueditor/',include('DjangoUeditor.urls' )),
四、修改model字段
django自帶的富文本編輯框為models.Textfield()
from DjangoUeditor.models import UEditorField
class Course(models.Model):
name = models.CharField(max_length=20, verbose_name='課程名稱')
desc = models.TextField(verbose_name='課程描述')
detail = UEditorField(verbose_name='課程詳情',width=600, height=300, toolbars="full", imagePath="course/ueditor/", filePath="course/ueditor/", upload_settings={"imageMaxSize":1204000},default='')
說明:
width,height :編輯器的寬度和高度,以像素為單位。imagePath :圖片上傳后保存的路徑,如"images/",實現上傳到"{{MEDIA_ROOT}}/images"文件夾。 注意:如果imagePath值只設置文件夾,則未尾要有"/" imagePath可以按python字符串格式化:如"images/%(basename)s_%(datetime)s.%(extname)s"。這樣如果上傳test.png,則文件會 被保存為"{{MEDIA_ROOT}}/images/test_20140625122399.png"。 filePath : 附件上傳后保存的路徑,設置規則與imagePath一樣。更多用法
五、xadmin中添加插件ueditor
由於已經將xadmin源文件拷貝到了項目下,本文為extra_apps/xadmin,在xadmin下的plugin中新建一個ueditor.py文件,里面寫入如下:
import xadmin
from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView
from DjangoUeditor.models import UEditorField
from DjangoUeditor.widgets import UEditorWidget
from django.conf import settings
class XadminUEditorWidget(UEditorWidget):
def __init__(self,**kwargs):
self.ueditor_options=kwargs
self.Media.js = None
super(XadminUEditorWidget,self).__init__(kwargs)
class UeditorPlugin(BaseAdminPlugin):
def get_field_style(self, attrs, db_field, style, **kwargs):
if style == 'ueditor':
if isinstance(db_field, UEditorField):
widget = db_field.formfield().widget
param = {}
param.update(widget.ueditor_settings)
param.update(widget.attrs)
return {'widget': XadminUEditorWidget(**param)}
return attrs
def block_extrahead(self, context, nodes):
js = '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.config.js") #自己的靜態目錄
js += '<script type="text/javascript" src="%s"></script>' % (settings.STATIC_URL + "ueditor/ueditor.all.min.js") #自己的靜態目錄
nodes.append(js)
xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView)
xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
六、將ueditor添加到plugin下的_init_中
PLUGINS = ( ... 'ueditor', )
七、將ueditor添加到adminx.py中
class CourseAdmin(object): ... style_fields = {"detail": "ueditor"}
八、前端頁面轉義
瀏覽器為了web安全在對后端傳來的html代碼會進行轉義,會將<>等符號進行轉義,因此要對頁面設置過濾器防止字符轉義
{% autoescape off %} {{ course.detail }} {% endautoescape %}