一、安裝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是False
if 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 MDTextField
class 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 Content
class 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 = 15
admin.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 forms
class MDEditorModleForm(forms.ModelForm):
class Meta:
model = Content
fields = '__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>