【Django】django-mdeditor富客户端并前端高亮展示

Published April 20, 2020, 2:50 a.m. by admin

django-mdeditor配置

安装

pip install django-mdeditor

在INSTALLED_APPS中添加mdeditor,

修改的文件为:settings.py

INSTALLED_APPS = [
#...
    'mdeditor'
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'

全局url配置路径

在Zsite站点的urls.py设置:

from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
#...
    url(r'mdeditor/', include('mdeditor.urls')),
]

if settings.DEBUG:
        # static files (images, css, javascript, etc.)
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在Zblog应用中的models.py中添加。

from mdeditor.fields import MDTextField

#...
     body = MDTextField()

Admin的界面如下:

编辑views.py视图

用于前段展示,在views.py视图,添加如下: * body用markdown渲染

import markdown

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                                   status='published',
                                   publish__year=year,
                                   publish__month=month,
                                   publish__day=day)
    post.body = markdown.markdown(post.body,
                                  extensions=[
                                     'markdown.extensions.extra',
                                     'markdown.extensions.codehilite',
                                     'markdown.extensions.toc',
                                  ])

渲染html模板

detail.html修改了body部分:

  {{ post.body|safe }}

代码高亮

安装

pip install Pygments 
$ pwd
/home/zsd/ZDjango/Zsite/Zblog/static/css
$ pygmentize -S default -f html -a .codehilite > code.css

放入到static/css目录中。引用。

{% load static %}
<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}{% endblock %}</title>
  <link href="{% static "css/blog.css" %}" rel="stylesheet">
  <link href="{% static "css/code.css" %}" rel="stylesheet">
</head>

同类文章

【Django】Django 数据导入和导出

【Django】创建Zstockweb

【Django】Site matching query does not exist

【Django】Django入门

0 次评论

没有任何评论

添加一条评论