Xadmin集成富文本编辑器ueditor

时间:2022-12-25 20:19:22

在xadmin中通过自定义插件,实现富文本编辑器,效果如下:

Xadmin集成富文本编辑器ueditor

1、首先,pip安装ueditor的Django版本:

pip install DjangoUeditor

 

2、之后需要添加到项目的settings.py文件的INSTALLED_APPS下面

Xadmin集成富文本编辑器ueditor

3、在urls.py文件中加入用于处理富文本的网址:

url(r'^ueditor/',include('DjangoUeditor.urls' ))

 

4、在model中使用UEditorField字段

from DjangoUeditor.models import UEditorField
class Blog(models.Model):
Name
=models.CharField(,max_length=100,blank=True)
Content
=UEditorField(u'内容 ',width=600, height=300,toolbars="full", imagePath="", filePath="",upload_settings={"imageMaxSize":1204000},settings={},command=None,event_handler=myEventHander(),blank=True)

UEditorField继承自models.TextField,因此你可以直接将model里面定义的models.TextField直接改成UEditorField即可。 定义UEditorField时除了可以直接传入models.TextField提供的参数外,还可以传入UEditorField提供的额外的参数 来控制UEditorField的外观、上传路径等。 UEditorField的参数如下:

  • width,height :编辑器的宽度和高度,以像素为单位。

  • toolbars :配置你想显示的工具栏,取值为mini,normal,full,代表小,一般,全部。如果默认的工具栏的按钮数量不符合您的要求,您可以在settings里面配置自己的显示按钮。参见后面介绍。

  • imagePath :图片上传后保存的路径,如"images/",实现上传到"{{MEDIA_ROOT}}/images"文件夹。 注意:如果imagePath值只设置文件夹,则未尾要有"/" imagePath可以按python字符串格式化:如"images/%(basename)s_%(datetime)s.%(extname)s"。这样如果上传test.png,则文件会 被保存为"{{MEDIA_ROOT}}/images/test_20140625122399.png"。 imagePath中可以使用的变量有:

    • time :上传时的时间,datetime.datetime.now().strftime("%H%M%S")
    • date :上传时的日期,datetime.datetime.now().strftime("%Y%m%d")
    • datetime :上传时的时间和日期,datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    • year : 年
    • month : 月
    • day : 日
    • rnd : 三位随机数,random.randrange(100,999)
    • basename : 上传的文件名称,不包括扩展名
    • extname : 上传的文件扩展名
    • filename : 上传的文件名全称
  • filePath : 附件上传后保存的路径,设置规则与imagePath一样。

  • upload_settings : 字典值, 例:upload_settings={ imagePathFormat:"images/%(basename)s_%(datetime)s.%(extname)s", imageMaxSize:323232 fileManagerListPath:"files" }

    • upload_settings的内容就是ueditor/php/config.json里面的配置内容,因此,你可以去看config.json或者官方文档内容来决定 该如何配置upload_settings,基本上就是用来配置上传的路径、允许上传的文件扩展名、最大上传的文件大小之类的。
    • 上面的imagePath和filePath被单独提取出来配置,原因是因为这两个参数是最常使用到的,imagePath就相当于upload_settings里面的 imagePathFormat,filePath就相当于upload_settings里面的filePathFormat。
    • 您upload_settings里面设置了imagePathFormat,也可以在UeditorField里面设置imagePath,效果是一样的。但是如果两者均设置, 则imagePath优先级更高。
    • 涂鸦文件、截图、远程抓图、图片库的xxxxPathFormat如果没有配置,默认等于imagePath.
    • 远程文件库的xxxxPathFormat如果没有配置,默认等于filePath.
  • settings : 字典值,配置项与ueditor/ueditor.config.js里面的配置项一致。

  • command : 可以为Ueditor新增一个按钮、下拉框、对话框,例:

  Description = UEditorField(u'描述', blank=True, toolbars="full",imagePath="cool/", settings={"a": 1},command=[myBtn(uiName="mybtn1", icon="d.png", title=u"1摸我",ajax_url="/ajaxcmd/"),myCombo(uiName="myCombo3",title=u"ccc",initValue="aaa")])

 

5、创建ueditor插件

在项目中xadmin/Plugins中创建插件ueditor.py,写入下面代码:

# -*- coding: utf-8 -*-
import xadmin
from django.db.models import TextField
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_fiels_style(self, attrs, db_field, style, **kwargs):
"""
接收adminx中的style_fields键值对,分别赋值给db_field,style
"""
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文件
"""
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)

 

6、将ueditor写入xadmin/Plugins/__init__.py文件中,__init__.py文件中有一个元组,存放xadmin的所有插件:

Xadmin集成富文本编辑器ueditor

7、在某一个app的adminx.py文件中指明哪个字段使用ueditor样式:

Xadmin集成富文本编辑器ueditor

8、有一个问题,当我们在富文本中写入非文本的内容时,页面不能正常显示内容:

Xadmin集成富文本编辑器ueditor

Xadmin集成富文本编辑器ueditor

加入了一个表情,显示的确实一段HTML代码。这是Django的CSRF防范的一种机制,它会对用户输入的字符进行转义

Xadmin集成富文本编辑器ueditor

实际的网页源码是这样的。如果要正常显示这部分的内容,需要用到Django模板一个过滤器:

Xadmin集成富文本编辑器ueditor

Xadmin集成富文本编辑器ueditor

 

 

DjangoUeditor源码地址:https://github.com/zhangfisher/DjangoUeditor

参考:http://coding.imooc.com/class/78.html