当前位置:首页 > 技术 > 正文内容

在Django中集成CKEditor5并实现博客文章编辑与展示

访客 技术 2026年6月15日 1

在Django项目中集成CKEditor5以提供富文本编辑功能,可以显著提升用户体验。以下是完整的配置和使用步骤:

  1. 安装CKEditor5对应的Django包:
sudo pip3 install django-ckeditor-5
  1. settings.py文件中将django_ckeditor_5添加到INSTALLED_APPS列表中:
INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_ckeditor_5',  # 添加此项
    ...
]
  1. 配置CKEditor5的设置项(示例配置):
import os

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

custom_palette = [
    {'color': 'hsl(4, 90%, 58%)', 'label': '红色'},
    {'color': 'hsl(340, 82%, 52%)', 'label': '粉色'},
    {'color': 'hsl(291, 64%, 42%)', 'label': '紫色'}
]

RICH_TEXT_CONFIGS = {
    'basic': {
        'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote'],
    },
    'advanced': {
        'blockToolbar': ['paragraph', 'heading1', 'heading2', '|', 'bulletedList', 'numberedList', '|', 'blockQuote'],
        'toolbar': [
            'heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'underline', 'strikethrough', 'code',
            'subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage',
            'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', 'imageUpload', '|',
            'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable'
        ],
        'image': {
            'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft', 'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side'],
            'styles': ['full', 'side', 'alignLeft', 'alignRight', 'alignCenter']
        },
        'table': {
            'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties'],
            'tableProperties': {'borderColors': custom_palette, 'backgroundColors': custom_palette},
            'tableCellProperties': {'borderColors': custom_palette, 'backgroundColors': custom_palette}
        },
        'fontFamily': {
            'options': ['微软雅黑', '宋体', '黑体', '仿宋', '楷体', 'Arial', 'Times New Roman'],
            'supportAllValues': True
        },
        'fontSize': {
            'options': [
                {'model': '56px', 'title': '初号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '48px', 'title': '小初', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '34.7px', 'title': '一号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '32px', 'title': '小一', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '29.3px', 'title': '二号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '24px', 'title': '小二', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '21.3px', 'title': '三号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '20px', 'title': '小三', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '18.7px', 'title': '四号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '16px', 'title': '小四', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '14px', 'title': '五号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '12px', 'title': '小五', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '10px', 'title': '六号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '8.7px', 'title': '小六', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '7.3px', 'title': '七号', 'view': {'styles': {'font-size': '14px'}}},
                {'model': '6.7px', 'title': '八号', 'view': {'styles': {'font-size': '14px'}}}
            ],
            'supportAllValues': True
        }
    }
}
  1. 修改项目的urls.py文件以支持CKEditor5的静态资源和媒体文件:
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('ckeditor5/', include('django_ckeditor_5.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. 在应用的models.py中定义一个模型类来存储文章内容:
from django.db import models
from django_ckeditor_5.fields import CKEditor5Field

class Article(models.Model):
    title = models.CharField(max_length=200, verbose_name='标题')
    content = CKEditor5Field(config_name='advanced', verbose_name='内容')

    def __str__(self):
        return self.title
  1. 创建表单类以便于在前端页面中使用CKEditor5:
from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('title', 'content')
        widgets = {
            'content': forms.Textarea(attrs={'class': 'django_ckeditor_5'})
        }
  1. admin.py中注册模型并配置管理界面:
from django.contrib import admin
from .models import Article

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ('title', 'content')
  1. 更新数据库结构并收集静态文件:
python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic
  1. 在应用的views.py中创建视图函数用于处理文章提交和展示:
from django.shortcuts import render, get_object_or_404
from .forms import ArticleForm
from .models import Article

def create_article(request):
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'form-post-finished.html')
    else:
        form = ArticleForm()
    return render(request, 'create-article.html', {'form': form})

def article_list(request):
    articles = Article.objects.all()
    return render(request, 'article-list.html', {'articles': articles})

def view_article(request, article_id):
    article = get_object_or_404(Article, id=article_id)
    return render(request, 'view-article.html', {'article': article})
  1. 配置应用的urls.py以映射上述视图函数:
from django.urls import path
from . import views

urlpatterns = [
    path('create/', views.create_article, name='create_article'),
    path('list/', views.article_list, name='article_list'),
    path('view/<int:article_id>/', views.view_article, name='view_article')
]
  1. 创建HTML模板文件以呈现表单和文章列表:
<!-- create-article.html -->
<form method="post">
    {% csrf_token %}
    <p>标题:{{ form.title }}</p>
    <p>内容:{{ form.content }}</p>
    <button type="submit">提交</button>
</form>

<!-- article-list.html -->
 {% for article in articles %} - [{{ article.title }}](<{% url 'view_article' article.id %}>)
 {% endfor %} 

<!-- view-article.html -->
<h1>{{ article.title }}</h1>
<div>{{ article.content|safe }}</div>

至此,您已经成功集成了CKEditor5并在Django中实现了简单的博客功能。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。