DjangoUeditor是在Py2上开发的,DjangoUeditor3解决了对Py3的兼容性问题。但在使用表单功能,引入DjangoUeitor.forms.UEditorField时,会出现widgets包无法引入的问题。所以为了方便修改和项目的维护,我把DjangoUeditor做成项目自身的APP引入。
一、环境配置
1.项目内创建DjangoUeditor app
python manage.py startapp DjangoUeditor
2. 下载DjangoUeditor3到本地,解压。
复制文件夹DjangoUeditor3-master\DjangoUeditor\static\ueditor到项目\static\下。
复制DjangoUeditor3-master\DjangoUeditor\templates下文件到项目templates。
复制DjangoUeditor3-master\DjangoUeditor\下其他文件到项目DjangoUeditor下。
3.配置
settings.py,
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,os.path.join(BASE_DIR,'apps'))
# 设置上传文件的路径
MEDIA_URL = "/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
INSTALLED_APPS = [
'DjangoUeditor', # 添加新建app到项目
]
STATIC_URL = '/static/' # 配置static路径
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('ueditor/', include('DjangoUeditor.urls' )),
path('', index, name = 'index'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
二、后台使用
1.创建UEditorField字段
引入DjangoUeditor.modelsl.UEditorField,用法与FileField类型。但会多一些可设的参数,网上很多,查找不难,需要注意的是,在设置文件或图片的路径时,如果引入日期,格式需要注意,用法与FileField的upload_to存在一定的区别,最好使用官方提到的指定函数的方法:
from django.db import models
from datetime import datetime
from DjangoUeditor.models import UEditorField
def getImagePath(model_name):
return "course/%s/image/%d/%d/"%(model_name, datetime.now().month, datetime.now().day)
class Resource(models.Model):
teletext = UEditorField(verbose_name='信息', imagePath=getImagePath('resource'), null=True, blank=True,
toolbars = "full", width=800, height=250)
2. admin.py内正常配置。
三、前端显示
富文本在数据库内保存的是html代码,前端取消掉转义,直接使用便可:
{% autoescape off %}
{{ course.teletext }}
{% endautoescape %}
四、前端引入富文本编辑框
正如官方所说,在表单中使用,与常规form没有差别,但因为兼容性问题,需要对DjangoUeditor\forms.py进行小的修改,否则会出现widgets包无法引入的问题。