python 后台 安裝 富文本編輯


前言

  當然需要安裝一些后台只能輸入一些文本編輯器,不然這樣多少不美觀呀

   當然python 有 safe 可以把后台的標簽轉換 ,

    還有 striptags   這個是換成html 格式的,但不會加粗或者啥之類的 

 

安裝編輯器

你的項目:我的是mysite

>>pip install django-ckeditor

他會自動幫你安裝一個django-js-asset 這個js解釋器 ,哈

然后在

注冊應用'ckeditor'

mysite\setting.py 修改

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',#引入本地相對路徑
    'blog',
    'ckeditor', #添加這個
]

 

配置model

在blog \models.py下的修改

把字段改成 RichTextField

from django.db import models
from django.contrib.auth.models import User
from ckeditor.fields import  RichTextField  #引入庫
# Create your models here.

class BlogType(models.Model):
    type_name = models.CharField(max_length=20)
    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)
    #context = models.TextField()
    context = RichTextField()  #替換便簽
    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: %s>" % self.title

    class Meta:
        ordering = ['-created_time']  # 按照created_time倒序排序

在操作和更新數據庫

python manage.py makemigrations
python manage.py migrate

在運行 

python manage.py runserver

打開后台界面出現下方的文本 :完美

修改繁體字  -> 簡體字

mysite\setting.py 修改

LANGUAGE_CODE = 'zh-hans'

 

安裝圖片上傳功能

 目錄下輸入:

pip install pillow

在注冊 ckeditor_oploader

mysite/settings.py

  最后一行加入 ‘ckeditor_oploader’

配置圖片url

mysite/settings.py

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

# 配置ckeditor
CKEDITOR_UPLOAD_PATH = 'upload/'

然后新建文件夾

mysite 下 media 文集夾

上傳的圖片就會到media 這個文件夾里面了

  配置路徑

mysite/urls.py

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')), #這個
    path('blog/', include('blog.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)  #這個

在把字段改為RichTextUploadingField

在blog \models.py下的修改

from ckeditor_uploader.fields import  RichTextUploadingField
...
    #context = models.TextField()
    context = RichTextUploadingField()

最后 在操作和更新數據庫

數據遷移  在操作和更新數據庫

python manage.py makemigrations
python manage.py migrate

在運行 

 

python manage.py runserver

 

在上傳圖片  ,選擇圖片 ,上傳到服務器上 ,完美 哈哈

 

    Django 也是依賴 第3方庫來開發的,哈哈 node 有點相似 

ok ,繼續加油吧

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM