Django-富文本

1.创建app

python manage.py startapp booktest

2.安装富文本库

pip install django-tinymce

3.setting添加booktest,配置文件存放位置


INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
    'tinymce',
]

TINYMCE_DEFAULT_CONFIG = {
    'theme': 'advanced',
    'width': 600,
    'height': 400,
}


4.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
    re_path(r'^tinymce/', include('tinymce.urls')),
]

5.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^htmlEditor/$', views.htmlEditor),
    re_path(r'^htmlEditorHandle/$', views.htmlEditorHandle),

]

注:最新版本2.0以上使用path 或者re_path

6.编写富文本 booktest/models

from django.db import models
from tinymce.models import HTMLField


class AreaInfo(models.Model):
    title = models.CharField(max_length=20)
    parea = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)


class Test1(models.Model):
    content = HTMLField()


7.编写富文本admin 后台界面booktest/admin

from django.contrib import admin
from .models import *

admin.site.register(Test1)


8.views编辑

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from .models import *
from django.views.decorators.cache import cache_page
from django.core.cache import cache


# 自定义编辑器
def htmlEditor(request):
    return render(request, 'booktest/htmlEditor.html')


def htmlEditorHandle(request):
    html = request.POST['hcontent']
    # test1=Test1.objects.get(pk=1)
    # test1.content=html
    # test1.save()
    test1 = Test1()
    test1.content = html
    test1.save()
    context = {'content': html}
    return render(request, 'booktest/htmlShow.html', context)

作者: 温先生

嗨,我是温国力 ,Gerry是我的英文名。一名热衷于编程的开发者,主要专注于PHP、Python、go、区块链的开发。此博客编写了开发心得、读书心得、生活娱乐,随时等待你的关注。

发表评论