搭建自己的博客(十三):为博客后台添加ckeditor富文本编辑器(代码片段)

felixwang2 felixwang2     2023-01-20     260

关键词:

使用django默认的编辑器感觉功能太少了,所以集成一下富文本编辑器。

1、安装和使用

(1)、安装

pip install django-ckeditor

(2)、注册应用

在django的settings中添加‘ckeditor’的app

(3)、配置models

将需要用到富文本编辑器的字段改成RichTextField

上面三步配置过后是不能上传图片的,下面配置上传图片的功能。

(4)、安装pillow库

pip install pillow

(5)、注册应用

添加‘ckeditor_uploader‘这个app

(6)、在settings指定图片上传的目录

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

# 配置ckeditor
CKEDITOR_UPLOAD_PATH=upload/

(7)、在urls中指定要上传的网址

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path(‘‘, views.home, name=home),  # 主页路径
    path(admin/, admin.site.urls),
    path(ckeditor, include(ckeditor_uploader.urls)),  # 配置上传url
    path(blog/, include(blog.urls)),  # 博客app路径
]

# 设置ckeditor的上传
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

(8)、配置model

把字段改成RichTextUploadingField字段类型

(9)、官方文档

上面这几步差不多就行了,还需要扩展功能,前往-》官方文档

2、变化的部分:

技术分享图片

3、上代码

技术分享图片
# 引用模板 #
% extends ‘base.html‘ %

% load staticfiles %
% block header_extends %
    <link rel="stylesheet" href="% static ‘blog/blog.css‘ %">
% endblock %


# 标题 #
% block title %
     blog.title 
% endblock %

# 内容#
% block content %
    <div class="container">
        <div class="row">
            <div class="col-6 offset-1">
                <ul class="blog-info-description">
                    <h3> blog.title </h3>
                    <li>作者: blog.author </li>
                    # 时间过滤器让时间按照自己需要的格式过滤 #
                    <li>发布日期: blog.created_time|date:"Y-m-d H:n:s" </li>
                    <li>分类:
                        <a href="% url ‘blogs_with_type‘ blog.blog_type.pk %">
                             blog.blog_type 
                        </a>
                    </li>
                </ul>
                <p class="blog-content"> blog.content|safe </p>


                <p>上一篇:
                    % if previous_blog %
                       <a href="% url ‘blog_detail‘ previous_blog.pk %"> previous_blog.title </a>
                    % else %
                        <span>没有了</span>
                    % endif %
                </p>
                <p>下一篇:
                    % if next_blog %
                        <a href="% url ‘blog_detail‘ next_blog.pk %"> next_blog.title </a>
                    % else %
                        <span>没有了</span>
                    % endif %
                </p>
            </div>
        </div>
    </div>


% endblock %

% block js %
    <script>
        $(".nav-blog").addClass("active").siblings().removeClass("active");
    </script>
% endblock %
blog_detail.html
技术分享图片
from django.db import models
from django.contrib.auth.models import User
from ckeditor_uploader.fields import RichTextUploadingField


# Create your models here.

# 博客分类
class BlogType(models.Model):
    type_name = models.CharField(max_length=15)  # 博客分类名称

    def __str__(self):  # 显示标签名
        return self.type_name


# 博客
class Blog(models.Model):
    title = models.CharField(max_length=50)  # 博客标题
    blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING)  # 博客分类
    content = RichTextUploadingField()  # 博客内容,使用富文本编辑
    author = models.ForeignKey(User, on_delete=models.DO_NOTHING)  # 博客作者
    created_time = models.DateTimeField(auto_now_add=True)  # 博客创建时间
    last_updated_time = models.DateTimeField(auto_now=True)  # 博客更新事件

    def __str__(self):  # 显示标题名
        return "<Blog:>".format(self.title)

    class Meta:
        ordering = [-created_time]  # 定义排序规则,按照创建时间倒序
models.py
技术分享图片
"""
Django settings for myblog project.

Generated by ‘django-admin startproject‘ using Django 2.1.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ea+kzo_5k^[email protected]([email protected]*+w5d11=0mp1p5ngr

# SECURITY WARNING: don‘t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    blog.apps.BlogConfig,  # 将自己创建的app添加到设置中
    ckeditor,
    ckeditor_uploader,
]

MIDDLEWARE = [

    django.middleware.security.SecurityMiddleware,
    django.contrib.sessions.middleware.SessionMiddleware,

    django.middleware.common.CommonMiddleware,
    django.middleware.csrf.CsrfViewMiddleware,
    django.contrib.auth.middleware.AuthenticationMiddleware,
    django.contrib.messages.middleware.MessageMiddleware,
    django.middleware.clickjacking.XFrameOptionsMiddleware,
    blog.middleware.mymiddleware.My404,  # 添加自己的中间件
]

ROOT_URLCONF = myblog.urls

TEMPLATES = [
    
        BACKEND: django.template.backends.django.DjangoTemplates,
        DIRS: [
            os.path.join(BASE_DIR, templates),
        ],
        APP_DIRS: True,
        OPTIONS: 
            context_processors: [
                django.template.context_processors.debug,
                django.template.context_processors.request,
                django.contrib.auth.context_processors.auth,
                django.contrib.messages.context_processors.messages,
            ],
        ,
    ,
]

WSGI_APPLICATION = myblog.wsgi.application

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = 
    # ‘default‘: 
    #     ‘ENGINE‘: ‘django.db.backends.sqlite3‘,
    #     ‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
    # 
    default: 
        ENGINE: django.db.backends.mysql,
        NAME: myblogs,  # 要连接的数据库,连接前需要创建好
        USER: root,  # 连接数据库的用户名
        PASSWORD: felixwang,  # 连接数据库的密码
        HOST: 127.0.0.1,  # 连接主机,默认本级
        PORT: 3306  # 端口 默认3306
    


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        NAME: django.contrib.auth.password_validation.UserAttributeSimilarityValidator,
    ,
    
        NAME: django.contrib.auth.password_validation.MinimumLengthValidator,
    ,
    
        NAME: django.contrib.auth.password_validation.CommonPasswordValidator,
    ,
    
        NAME: django.contrib.auth.password_validation.NumericPasswordValidator,
    ,
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

# LANGUAGE_CODE = ‘en-us‘
# 语言
LANGUAGE_CODE = zh-hans

# TIME_ZONE = ‘UTC‘
# 时区
TIME_ZONE = Asia/Shanghai

USE_I18N = True

USE_L10N = True

# 不考虑时区
USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = /static/
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

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

# 配置ckeditor
CKEDITOR_UPLOAD_PATH=upload/


# 自定义参数
EACH_PAGE_BLOGS_NUMBER = 7
settings.py
技术分享图片
"""myblog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path(‘‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path(‘‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path(‘blog/‘, include(‘blog.urls‘))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path(‘‘, views.home, name=home),  # 主页路径
    path(admin/, admin.site.urls),
    path(ckeditor, include(ckeditor_uploader.urls)),  # 配置上传url
    path(blog/, include(blog.urls)),  # 博客app路径
]

# 设置ckeditor的上传
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urls.py

 

hexo个人博客搭建(代码片段)

老早就想搭建一个属于自己的个人博客了,之前也弄过一个,后台到前端完全原生自主编写,可是终究还是太年轻,很多东西都不会,也不懂得坚持,慢慢就荒废了。加上几次的服务器变更,再加上工作没精力打理,之前的个人... 查看详情

wordpress搭建自己的博客~

...链接:https://cn.wordpress.org/wordpress是一款开源的PHP框架,搭建个人博客网站最实用的选择之一,甚至你都不需要懂PHP你就可以搭建自己的个人网站。提供强大的后台文章管理和插件及主题管理,几乎可以满足个人网站所有需求。... 查看详情

《全栈营销之如何制作个人博客》之二:php环境安装及个人博客后台搭建让你的博客跑起来

...,这一节我们讨论一下PHP环境的安装,及个人博客后台的搭建,让你的博客在正常的PHP环境中运行起来,你就可以进行后台的数据管理,添加,修改,删除什么的。我们开发这个博客,主要讲的是怎么快速开发一个个人博客,所... 查看详情

django搭建个人博客平台4---后台admin优化simpleui和导入导出(代码片段)

文章目录Django搭建个人博客平台4---后台admin优化、simpleui和导入导出Admin优化展示字段设置添加过滤器添加点击链接可编辑字段simpleui基本使用进阶重写simple-ui的模板html文件左侧边栏自定义添加项其他小配置导入导出插件安装使... 查看详情

个人的博客搭建(持续更新)(代码片段)

...近的CSDN的博客阅读体验非常的糟糕,恰好自己也一直想搭建一个属于自己的网站,放下自己的技术心得情感体会,从零开始慢慢搭建项目磨练技术,以后也把自己新习得的技术放在里面增加自己的学习乐趣。一,搭建基本的项... 查看详情

如何搭建个人开源博客系统框架

一、先到域名注册商那注册购买网站域名和网站空间或服务器;二、选择自己相对熟悉的博客系统并下载,其中asp环境的比较多用户的开源博客系统主要有:zblog和pjblog;PHP博客开源系统主要有:wordpress,百度搜索它们的名称后... 查看详情

github博客搭建

今天折腾了GitHubBlog的配置,在此记录下1.创建名字为: “用户名”.github.io的仓库2.fork一个blog模板(这一步自己的能力,将不断的学习,争取自己能够写)。3.下载一个名字为GithubDesktop的软件,这个软件可以在桌面管... 查看详情

运用bt在centos下搭建一个博客论坛(代码片段)

...很希望有自己的工作站,就是自己的服务器,自己给自己搭建一个博客或者是论坛,用于自己来写博客和搭建网站论坛。现在我们就用一个简单的方法来教大家如何30分钟内部署一个博客网站。  首先,你要有一个自己的服务... 查看详情

centos7.6搭建wordpress博客(代码片段)

需求:因公司推广部业务需求,搭建WordPress博客网站介绍:WordPress是使用PHP语言开发的博客平台,用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。WordPress是... 查看详情

博客园为自己首页添加背景音乐

以网易云音乐为例:选歌点击生成外链播放器会跳转到iframe找到下面的那段HTML代码,并复制那段代码并将开头的iframeframeborder="no"替换成embed最后面的iframe也替换成embed,将代码粘贴到博客园设置-首页HTML代码框保存。auto=1为自动... 查看详情

搭建一个自己的hexo博客(保姆级教程)(代码片段)

搭建一个自己的Hexo博客-保姆级教程-非常详细Hexo简介环境安装node.jsgitcnpmhexoGithub/Gitee配置创建仓库搭建博客初始化将博客部署到Github/Gitee上主题寻找主题下载主题修改主题内容主题插件置顶文章私密文章加密404页面文章目录图... 查看详情

vitepress+giteepages搭建自己的博客网站(代码片段)

概述“不写博客的GISer不是一个好程序员”。所以,好多程序员会保留着写博客的习惯,一方面记录自己的学习成果或者解决某个问题的方法,一方面能够帮助到他人,再一方面也能够督促自己多学点东西……这... 查看详情

利用wordpress搭建自己的博客(代码片段)

利用Wordpress搭建自己的博客目录利用Wordpress搭建自己的博客一、首先搭建好LNMP环境二、安装Wordpress2.1.1下载Wordpress安装包一、首先搭建好LNMP环境关于环境的搭建请看博文:https://www.cnblogs.com/woaiyunwei/p/12873431.html二、安装Wordpress2.1... 查看详情

window下jekyll+github搭建自己的博客

1.安装git  1-1.下载git,这里给出一个地址:http://git-scm.com/downloads  1-2.安装,一路next  1-3.配置git环境变量,将git安装路径中bin的位置xxGitin和git-core的位置xxGitlibexecgit-core添加到path环境变量2.安装Jekyll  2-1.安装RubyInstaller... 查看详情

github+jekyll个人博客搭建

...blog.csdn.net/Hanghang_/article/details/78944672跟着这个博客一步步搭建,从jekyll官网上找到自己喜欢的主题。是在_posts文件夹下面添加markdown文件,我准备采用的md文件编辑器是VScode怎么在里面添加图片呢?首先是将图片传到GitHub的image文... 查看详情

搭建自己的技术博客系列使用hexo搭建一个精美的静态博客

1、安装Git和nodejshttps://hexo.io/zh-cn/docs/?2安装Hexohttps://hexo.io/zh-cn/?3、更换伊卡洛斯主题https://github.com/ppoffice/hexo-theme-icarus?配置新主题:https://blog.zhangruipeng.me/hexo-theme-icarus/uncategorized/getti 查看详情

hexo+github,搭建属于自己的博客

摘录自:http://www.jianshu.com/p/465830080ea91.github的准备  账号密码 建立Repository建立与你用户名对应的仓库,仓库名必须为【your_user_name.github.io】 建立一个仓库blog不要勾选initialize(这一步可有可无第二种情况)2.客户端的git... 查看详情

搭建自己的博客:创建表,创建超级用户(代码片段)

接上一篇搭建完成之后,开始构建一些表了。一篇博客首先需要一个表来存放博客,然后一篇博客应该需要不同的标签来分类,还应该有作者。下面动手创建表。作者表暂时准备使用django自带的user表1、创建博客标签表和博客表... 查看详情