要在前端使用 Django-MDEditor 呈现 Markdown 内容,你需要按照以下步骤操作:
pip install django-mdeditor
settings.py
文件中添加 mdeditor
到 INSTALLED_APPS
:INSTALLED_APPS = [
# ...
'mdeditor',
# ...
]
urls.py
文件中添加 MDEditor 的 URL 配置:from django.urls import path, include
urlpatterns = [
# ...
path('mdeditor/', include('mdeditor.urls')),
# ...
]
models.py
文件中:from django.db import models
from mdeditor.fields import MDTextFormField
class Article(models.Model):
title = models.CharField(max_length=100)
content = MDTextFormField()
python manage.py makemigrations
python manage.py migrate
forms.py
文件中:from django import forms
from mdeditor.widgets import MDEditWidget
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'content']
widgets = {
'content': MDEditWidget(),
}
views.py
文件中:from django.shortcuts import render
from .models import Article
from .forms import ArticleForm
def article_create(request):
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
# 重定向或其他操作
else:
form = ArticleForm()
return render(request, 'article_create.html', {'form': form})
def article_detail(request, pk):
article = Article.objects.get(pk=pk)
return render(request, 'article_detail.html', {'article': article})
safe
过滤器呈现 Markdown 内制内容。例如,在 article_detail.html
文件中:{% extends 'base.html' %}
{% block content %}
<h1>{{ article.title }}</h1>
{{ article.content|safe }}
{% endblock %}
领取专属 10元无门槛券
手把手带您无忧上云