Django博客开发:使用富文本编辑器(八)
在Django admin后台添加数据的时候,文章内容文本框想发布一篇图文并茂的文章需就得手写Html代码,这十分吃力,也没法上传图片和文件。这显然不是我等高大上程序猿想要的。

为提升效率,我们可以使用富文本编辑器添加数据。支持Django的富文本编辑器很多,这里我推荐使用DjangoUeditor,Ueditor是百度开发的一个富文本编辑器,功能强大。下面教大家安装如何使用DjangoUeditor。
1、首先我们先下载DjangoUeditor包
点击下面的链接进行下载!下载完成然后解压到项目根目录里。
https://www.django.cn/media/upfile/DjangoUeditor_20181010013851_248.zip
2、settings.py里注册APP
在INSTALLED_APPS里添加'DjangoUeditor'
myblog/settings.y
INSTALLED_APPS = [
'django.contrib.admin',
....
'DjangoUeditor', #注册APP应用
]
##验证是否已经增加正确,按住 ctrl 点击DjangoUdeitor,只要能跳转到目录即可;
3、myblog/urls.py里添加url。
myblog/urls.py
...
from django.urls import path, include
#留意上面这行比原来多了一个include
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.hello),
path('ueditor/', include('DjangoUeditor.urls')), #添加DjangoUeditor的URL
]
4、修改blog/models.py里需要使用富文本编辑器渲染的字段。这里面我们要修改的是Article表里的body字段。
把原来的:
blog/models.py
body = models.TextField()
修改成:
blog/models.py
from DjangoUeditor.models import UEditorField #头部增加这行代码导入UEditorField
body = UEditorField('内容', width=800, height=500,
toolbars="full", imagePath="upimg/", filePath="upfile/",
upload_settings={"imageMaxSize": 1204000},
settings={}, command=None, blank=True
)
留意里面的
imagePath="upimg/", filePath="upfile/"
上面步骤完成后,我们启动项目,进入文章发布页面。提示出错:
错误一:
File "C:\Python37\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
t = DEBUG_ENGINE.from_string(fh.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
查看错误栈最后一行发现是 编码问题 找到django 源码 "C:-packages.py" 332行位置 ,增加utf-8编码 open( encoding='utf-8'),问题解决:
def get_traceback_html(self):
"""Return HTML version of debug 500 HTTP error page."""
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open( encoding='utf-8') as fh:
t = DEBUG_ENGINE.from_string(fh.read())
c = Context(self.get_traceback_data(), use_l10n=False)
return t.render(c)
错误二:
render() got an unexpected keyword argument 'renderer'

我这里使用的是最新版本的Django2.1.1所以报错,解决办法很简单。打开这个文件的93行,注释这行即可。

修改成之后,重新刷新页面,就可以看到我们的富文本编辑器正常显示。

留意,如果我们在富文本编辑器里,上传图片,在编辑器内容里不显示上传的图片。那我们还需要进行如下设置,打开myblog/urls.py文件,在里面输入如下代码:
myblog/urls.py
....
from django.urls import path, include, re_path
#上面这行多加了一个re_path
from django.views.static import serve
#导入静态文件模块
from django.conf import settings
#导入配置文件里的文件上传配置
urlpatterns = [
path('admin/', admin.site.urls),
....
re_path('^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),#增加此行
]
随便测试了一篇文章:

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!