Django博客开发教程:使用富文本编辑器添加数据

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

2.jpg

为提升效率,我们可以使用富文本编辑器添加数据。支持Django的富文本编辑器很多,这里我推荐使用DjangoUeditor,Ueditor是百度开发的一个富文本编辑器,功能强大。下面教大家安装如何使用DjangoUeditor。

1、首先我们先下载DjangoUeditor包。点击下面的链接进行下载!下载完成然后解压到项目根目录里。

DjangoUeditor.zip

2、settings.py里注册APP,在INSTALLED_APPS里添加'DjangoUeditor',

myblog/settings.y
INSTALLED_APPS = [
    'django.contrib.admin',
    ....
    'DjangoUeditor', #注册APP应用
]

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/" 这两个是图片和文件上传的路径,我们上传文件,会自动上传到项目根目录media文件夹下对应的upimg和upfile目录里,这个目录名可以自行定义。有的人问,为什么会上传到media目录里去呢?那是因为之前我们在基础配置文章里,设置了上传文件目录media。

上面步骤完成后,我们启动项目,进入文章发布页面。提示出错:

render() got an unexpected keyword argument 'renderer'

3.jpg

错误页面上有提示,出错的地方是下面文件的93行。

F:\course\myblog\myblogvenv\lib\site-packages\django\forms\boundfield.py in as_widget, line 93

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

4.jpg

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

5.jpg

留意,如果我们在富文本编辑器里,上传图片,在编辑器内容里不显示上传的图片。那我们还需要进行如下设置,打开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}),#增加此行
]

设置好了之后,图片就会正常显示。这样我们就可以用DjangoUeditor富文本编辑器发布图文并茂的文章了。


文章评论 39

  • 请问 我按照老师您的方法 都做了 打开页面 没有任何反应是什么问题?

  • myblog/urls的的一个需要改就可以正常显示了。 from django.conf import settings 改为 from myblog import settings 意思是将项目根目录的settingsimport进来。 原文中的settings是全局settings,可实际django2.2里的全局settings是global_settings.py,并非settings.py。

  • 我的按照覆盖操作 一步一步添加后,启动Server 报错: ImportError: attempted relative import with no known parent package , 不知道是不是from . import settings as uSettings 出现问题,还是哪儿,老师有空指教一下!

  • 报错 In template D:\开发者工具\Python3\lib\site-packages\django-2.2.5-py3.7.egg\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19

    no such table: Learn520App_category 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> 28 {% endfor %} 29 </fieldset>

    大佬这个问题应该怎么解决

  • 请问我按照老师的方式操作,进入文章发布页显示的错误是

     no such table: blog_article
     Request Method:    GET
     Request URL:   http://127.0.0.1:8000/admin/blog/article/
     Django Version:    2.2.5
     Exception Type:    OperationalError
     Exception Value:   
     no such table: blog_article
     Exception Location:    C:\Users\12370\PycharmProjects\mysite\venv\lib\site-     packages\django\db\backends\sqlite3\base.py in execute, line 383
     Python Executable: C:\Users\12370\PycharmProjects\mysite\venv\Scripts\python.exe
     Python Version:    3.6.1

    而不是文章中的错误,应该如何修改呢,谢谢你。

  • 我点插入图片后,显示上传错误

  • 解决办法: settings设置中间件MIDDLEWARE内的参数注释掉'django.middleware.clickjacking.XFrameOptionsMiddleware'

    查找上传错误的原因: 上传图片时查看console显示 “Refused to display 'http://127.0.0.1:8000/ueditor/controller/?imageMaxSize=1204000&imagePathFormat=upimg%2F&filePathFormat=upfile%2F&action=uploadimage' in a frame because it set 'X-Frame-Options' to 'deny'.”

    寻找办法: Django的项目中默认设置了XFrameOptionsMiddleware的中间件,这个设置将对于X-Frame-Options的配置设置成了DENY。 在Django 3.0中,X_FRAME_OPTIONS的默认设置从SAMEORIGIN 变成了DENY 附带链接: https://www.cnblogs.com/lph970417/p/12896689.html

  • 问题:

    在进入admin的时候出现’set’ object is not reversible错误 发生版本: python3.6

    解决方案是在你的urls.py 中

    把{ } 改为[]

  • 先开始也出现了很多问题,后来回到前面两步,重新做了一遍,感觉很多问题都是因为作者说明的意思不理解导致的,重新做了一遍,我用的是django3.0发现好像出现的问题都差不多,目前还没看出来不同django版本之间的不同,很有趣,在学习中

  • 我这里有一个问题是在富文本上传单张图片的时候提示 “上传错误”,不懂什么原因,如果是批量上传的时候是没有的问题的。

  • 请问您这个问题解决了么?我也遇到了同样的问题,批量上传正常,单独一张图片就提示“上传错误”,但是后台没有报错。

  • 我还一直以为是DjangoUeditor这个包的问题,是我太蠢了,这个作用在文章这个类里面,实际上是需要进入后台编辑文章才能查看的,下面这个教程更加详细 https://blog.csdn.net/qianbin3200896/article/details/88389535?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

  • Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/article/add/ Django Version: 3.0.5 Exception Type: TypeError Exception Value:
    render() got an unexpected keyword argument 'renderer' Exception Location: C:\Users\CK\AppData\Local\Programs\Python\Python38\lib\site-packages\django\forms\boundfield.py in as_widget, line 92 Python Executable: E:\course\myblog\myblogvenv\Scripts\python.exe Python Version: 3.8.2 Python Path:
    ['E:\course\myblog', 'C:\Users\CK\AppData\Local\Programs\Python\Python38\lib\site-packages', 'E:\course\myblog', 'C:\Program Files\JetBrains\PyCharm 2019.1.2\helpers\pycharm_display', 'C:\Users\CK\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\CK\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\CK\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\CK\AppData\Local\Programs\Python\Python38', 'E:\course\myblog\myblogvenv', 'E:\course\myblog\myblogvenv\lib\site-packages', 'C:\Program Files\JetBrains\PyCharm ' '2019.1.2\helpers\pycharm_matplotlib_backend']

  • 上传失败错误

    解决办法: settings设置中间件MIDDLEWARE内的参数注释掉'django.middleware.clickjacking.XFrameOptionsMiddleware'

    查找上传错误的原因: 上传图片时查看console显示 “Refused to display 'http://127.0.0.1:8000/ueditor/controller/?imageMaxSize=1204000&imagePathFormat=upimg%2F&filePathFormat=upfile%2F&action=uploadimage' in a frame because it set 'X-Frame-Options' to 'deny'.”

    寻找办法: Django的项目中默认设置了XFrameOptionsMiddleware的中间件,这个设置将对于X-Frame-Options的配置设置成了DENY。 在Django 3.0中,X_FRAME_OPTIONS的默认设置从SAMEORIGIN 变成了DENY 附带链接: https://www.cnblogs.com/lph970417/p/12896689.html

  • <p>问题: no such table: blog_article Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/article/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: <br /> no such table: blog_article Exception Location: C:\Users\12370\PycharmProjects\mysite\venv\lib\site- packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\12370\PycharmProjects\mysite\venv\Scripts\python.exe Python Version: 3.6.1

    解决办法: 请使用python manage.py makemigrations和python manage.py migrate 进行数据库迁移</p>

  • 问题:报错 In template D:\开发者工具\Python3\lib\site-packages\django-2.2.5-py3.7.egg\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 1

    参考:https://www.cnblogs.com/python-boy/p/11290606.html

  • 老师好,做到抛异常,我安装的是Django 最新的4.0版本,Python 3.10.2

    File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\DEV\python\myblog\myblog\urls.py", line 19, in <module> from django.conf.urls import include, url ImportError: cannot import name 'url' from 'django.conf.urls' (D:\DEV\python\myblog\venv\lib\site-packages\django\conf\urls__init__.py)

  • from .views import get_ueditor_controller from django.conf.urls import url

    urlpatterns = [ url(r'^controller/$', get_ueditor_controller), ]

  • ImportError: cannot import name 'url' from 'django.conf.urls' 富文本这个包老是报错,最近Django4.0 又移除了url 这个方法,暂时不明白咋整了,求指导...谢谢

  • Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\360安全浏览器下载\Python37_64\lib\threading.py", line 927, in _bootstrap_inner self.run() File "D:\360安全浏览器下载\Python37_64\lib\threading.py", line 870, in run self._target(self._args, self._kwargs) File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, kwargs) File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(args, kwargs) File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "D:\360安全浏览器下载\Python37_64\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\课上练习\Django\test\blog2\post\models.py", line 45, in <module> class Article(models.Model): File "D:\课上练习\Django\test\blog2\post\models.py", line 56, in Article settings={}, command=None, blank=True) File "D:\课上练习\Django\test\blog2\venv\lib\site-packages\django\db\models\fields__init__.py", line 2117, in init super().init(*args, kwargs) TypeError: init() got an unexpected keyword argument 'width' 请教一下添加富文本编辑器之后为什么那么多错误啊

  • renderer报错的地方 可以看这个链接https://www.cnblogs.com/python-boy/p/11290606.html

    还有就是DjangoUeditor\urls.py里修改 高级版本的话,使用from django.urls import re_path 而不是from django.urls import re_path

    #DjangoUeditor\urls.p
    from .views import get_ueditor_controller
    from django.urls import re_path
    # 这里需要修改from django.urls import url 为 from django.urls import path
    urlpatterns = [
        re_path(r&#x27;^controller/$&#x27;, get_ueditor_controller),
    ]