make django3.1 backend markdown support

django3.1 后台添加markdown支持

首先安装 django-mdeditor

python pip install django-mdeditor

settings.py 中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'mdeditor',
]

...
# add uploads文件夹
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') #uploads必须存在,且在项目目录下
MEDIA_URL = '/media/'

添加站点路由 mysite/urls.py

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include(('blog.urls','blog'),namespace='blog')),
path('mdeditor/',include('mdeditor.urls')),
]
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

修改blog下models.py中内容类型

导入MDTextField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django.db import models
from mdeditor.fields import MDTextField

# Create your models here.


class BlogPost(models.Model):
title = models.CharField(max_length= 150)

# body = models.TextField()
body = MDTextField()

create_time = models.DateTimeField()

def __str__(self):
return f"<BlogPost {self.title}>"

class Meta:
verbose_name ="文章"
verbose_name_plural = verbose_name

blog应用views.py

1
2
3
4
5
6
7
8
9
10
11
12

def details(request, blog_id):
blog = get_object_or_404 (BlogPost, pk=blog_id)
blog.body = markdown(blog.body, extensions=[
# 包含 缩写、表格等常用扩展
'markdown.extensions.extra',
# 语法高亮扩展
'markdown.extensions.codehilite',
#允许我们自动生成目录
'markdown.extensions.toc',
])
return render (request, 'blog_detail.html', {'blog': blog})

前台页面添加markdown css支持

1
<link rel="stylesheet" href="https://cdn.bootcss.com/github-markdown-css/3.0.1/github-markdown.css">

前台页面添加 safe渲染

1
2
{{ blog.title }}
{{ blog.body | safe }}

重新启动服务

python manage.py runserver 127.0.0.1:8000

坚持原创技术分享,您的支持将鼓励我继续创作!