DjangoUeditor的python2和python3版本安装方法有所不同,通过pip安装的为python2版本,python3需要下载解压直接放至项目根目录。
1、下载DjangoUeditor源码
https://github.com/twz915/DjangoUeditor3/
2、放置到项目根目录下
INSTALLED_APPS = [
'simpleui',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'service',
'DjangoUeditor',
]
4、设置url
所有的请求均通过url实现的,所以此处需要为DjangoUeditor注册url,该模块按照django的规则开发的,本质上是TextField的扩展。
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('ueditor/', include('DjangoUeditor.urls')),
]
5、在目标models中使用DjangoUeditor
from django.db import models
from DjangoUeditor.models import UEditorField
class Service(models.Model):
title = models.CharField(max_length=100, verbose_name='产品名称')
description = models.TextField(verbose_name='描述')
content = UEditorField(verbose_name='服务内容', width=960, height=600)
def __str__(self):
return self.title
class Meta:
verbose_name = verbose_name_plural = '服务设置'
本质上为继承DjangoUeditor的UEditorField,在字段属性中使用该model即可,具体选项可查看DjangoUeditor源码:
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.admin import widgets as admin_widgets
from .widgets import UEditorWidget, AdminUEditorWidget
class UEditorField(models.TextField):
"""
百度HTML编辑器字段,初始化时,可以提供以下参数
initial:初始内容
toolbars:提供工具按钮列表,取值为列表,如['bold', 'italic'],取值为:mini,normal,full,代表小,一般,全部
imagePath:图片上传的路径,如"images/",实现上传到"{{MEDIA_ROOT}}/images"文件夹
filePath:附件上传的路径,如"files/",实现上传到"{{MEDIA_ROOT}}/files"文件夹
"""
def __init__(self, verbose_name=None, width=600, height=300,
toolbars="full", imagePath="", filePath="",
upload_settings={}, settings={}, command=None,
event_handler=None, **kwargs):
self.ueditor_settings = locals().copy()
kwargs["verbose_name"] = verbose_name
del self.ueditor_settings["self"], self.ueditor_settings[
"kwargs"], self.ueditor_settings["verbose_name"]
super(UEditorField, self).__init__(**kwargs)
def formfield(self, **kwargs):
defaults = {'widget': UEditorWidget(attrs=self.ueditor_settings)}
defaults.update(kwargs)
if defaults['widget'] == admin_widgets.AdminTextareaWidget:
defaults['widget'] = AdminUEditorWidget(
attrs=self.ueditor_settings)
return super(UEditorField, self).formfield(**defaults)
# 以下支持south
try:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^DjangoUeditor\.models\.UEditorField"])
except:
pass
6、图片、文件上传的处理办法
MEDIA_ROOT
,不然编辑器不知道将文件放在什么地方:MEDIA_ROOT = os.path.join('media')
MEDIA_URL = '/media/'
顺便一并将MEDIA_URL一并设置,这是访问media资源时以什么字符显示在url中。
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('ueditor/', include('DjangoUeditor.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
这样无论是编辑器中,还是前端中都可以访问所上传的资源了。