Django使用markdown文本编辑器

2023-07-30 17:29:35 浏览数 (3)

安装:

代码语言:javascript复制
pip install django-mdeditor

在settings.py中加入app:

代码语言:javascript复制
INSTALLED_APPS = [
    #  原生app
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #  非原生app
    'mdeditor',
]

在settings.py中设置媒体路径(已存在媒体路径可以忽略):

代码语言:javascript复制
#  媒体
MEDIA_URL = '/upload/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')

在urls.py中设置媒体上传路由和mdeditor路由:

代码语言:javascript复制
from django.urls import path, include, re_path
from django.views.static import serve
from django.conf import settings

urlpatterns = [
    ...
    #  媒体文件路由
    re_path('upload/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}, name='upload'),
    path(r'mdeditor/', include('mdeditor.urls')),
]

后台模型的使用: 在models.py中创建模型:

代码语言:javascript复制
from mdeditor.fields import MDTextField

#  文章内容
class Contents(models.Model):
    id = models.AutoField(primary_key = True)
    title = models.CharField(max_length=30)
    #  文本字段
    content = MDTextField()
    time = models.DateTimeField()

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = '内容'
        verbose_name_plural = '内容'

前端界面的显示: 导入css,js文件,这些文件的路径在pythonLibsite-packagesmdeditorstatic中,将它拷贝至项目的静态文件目录使用即可(注意导入顺序):

代码语言:javascript复制
<!--mdeditor-->
<link rel="stylesheet" href="{% static 'editormd.preview.css' %}">
<script rel="script" src="{% static 'jquery.min.js' %}"></script>
<script rel="script" src="{% static 'marked.min.js' %}"></script>
<script rel="script" src="{% static 'prettify.min.js' %}"></script>
<script rel="script" src="{% static 'raphael.min.js' %}"></script>
<script rel="script" src="{% static 'underscore.min.js' %}"></script>
<script rel="script" src="{% static 'sequence-diagram.min.js' %}"></script>
<script rel="script" src="{% static 'flowchart.min.js' %}"></script>
<script rel="script" src="{% static 'jquery.flowchart.min.js' %}"></script>
<script rel="script" src="{% static 'editormd.js' %}"></script>

创建容器,编写js脚本:

代码语言:javascript复制
<div id="content">
    <h2>{{ contant.title }}</h2>
    <!--文本字段,注意js中的id名称对应div的id名称-->
    <div id="content_text">
        <textarea style="display: none;">{{ contant.content | safe }}</textarea>
        <script type="text/javascript">
            var testEditor;
            $(function() {
                testEditor = editormd.markdownToHTML("content_text", {
                });
            });
        </script>
    </div>
    <!--文本字段结束-->
    <span>{{ contant.time }}</span>
</div>

0 人点赞