一、安装markdown插件
pip install django-mdeditor
pip install markdown
二、在 settings 配置文件 INSTALLED_APPS 中添加 mdeditor:
INSTALLED_APPS = [...'mdeditor',]
三、插入图片没有地址,针对django3.0+修改 frame 配置,settings.py设置如下:
X_FRAME_OPTIONS = 'SAMEORIGIN' # 上传图片时,防止跨域 # django 3.0 + 默认为 deny
四、在 settings 中添加媒体文件的路径配置:
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'
在你项目根目录下创建 uploads/editor 目录,用于存放上传的图片。
五、在你项目的根 urls.py 中添加扩展url和媒体文件url:
我的django版本是4.2.5,设置如下
from django.conf import settings
from django.urls import include
from django.conf.urls.static import static...urlpatterns = [...path("mdeditor/", include('mdeditor.urls')),
]# 配置静态文件,这个很重要,不然上传的图片和文件无法被访问到,必须要引入blog/settings里面的debug,因为globle的debug是Falseif settings.DEBUG:urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
六、编写一个测试demo—model:
from django.db import models
from mdeditor.fields import MDTextFieldclass Content(models.Model):"""文章"""title = models.CharField(max_length=100)content = MDTextField()create_time = models.DateTimeField(auto_now_add=True)update_time = models.DateTimeField(auto_now=True)class Meta:db_table = '文章'verbose_name = '文章'verbose_name_plural = '文章'ordering = ['-create_time']def __str__(self):return self.title
七、向admin中注册model
from django.contrib import admin
from markdownx.admin import MarkdownxModelAdmin
from .models import Contentclass ContentAdmin(MarkdownxModelAdmin):# 显示哪些字段list_display = ('id', 'title', 'create_time', 'update_time')# 排序字段ordering = ("-create_time",)# 显示哪些字段可以点击跳转list_display_links = ("id", "title")# 搜索字段search_fields = ("title", "content")# 设置每页显示多少条数据list_per_page = 15admin.site.register(Content, ContentAdmin)
八、创建好Django admin 超级管理员账号python manage.py createsuperuser
然后运行 python manage.py makemigrations
和 python manage.py migrate
来创建你的model 数据库表.
登录 django admin后台,点击 '添加'操作,你会看到如下界面。
九、在前端中使用Markdown 编辑器,首先创建ModelForm类
from app.models import Content
from django.forms import ModelForm
from django import formsclass MDEditorModleForm(forms.ModelForm):class Meta:model = Contentfields = '__all__'def add(request):forms = MDEditorModleForm()if request.method == 'POST':forms = MDEditorModleForm(request.POST)if forms.is_valid():forms.save()return redirect('/index')else:print(forms.errors)return render(request, 'add.html', {'forms': forms})
前端代码:
{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>添加文章</title>
</head>
<body><h3>添加文章</h3><form method="post">{% csrf_token %}{{ forms.media }}{{ forms.as_p }}<p><input type="submit" value="立即保存"></p></form>
</body>
</html>