Django-Admin使用markdown编辑器

1、安装django-mdeditor模块

pip install django-mdeditor

2、注册mdeditor到APPS中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 新插入的corsheaders,之前的不
    'corsheaders',
    # 注册markdown的应用
    'mdeditor',
    'report',
]

3、设置markdown上传的图片保存路径

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 顺便配置下静态资源的根目录
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

4、配置mdeditor的路由

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve

from report.views import get_report
from restful_api.settings import STATIC_ROOT, MEDIA_ROOT

urlpatterns = [
    path('admin/', admin.site.urls),
    path('report/', get_report),
    # 配置mdeditor路由
    path(r'mdeditor/', include('mdeditor.urls')),
    # django关闭debug模式后,静态文件无法访问,这里要设置下静态文件的访问路由
    re_path(r'^static/(?P<path>.*)$', serve, {'document_root': STATIC_ROOT}),
    re_path(r'^media/(?P<path>.*)', serve, {"document_root": MEDIA_ROOT}),
]

关闭debug模式后,要使用命令把下载的第三方APP静态文件拷贝一份到static路径下

python manage.py collectstatic

5、在模型类中使用markdown字段

from django.db import models
from mdeditor.fields import MDTextField


class Report(models.Model):

    title = models.CharField(max_length=120, verbose_name="标题")
    content = MDTextField(max_length=1000, verbose_name="测试报告")

6、解决markdown上传成功,获取不到地址的问题

# settings.py中配置该值
X_FRAME_OPTIONS = 'SAMEORIGIN'
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页