富文本編輯器
概念
- 能夠設置文字樣式的頁面成為文本編輯器(帶有格式的文本信息)
tinyce 配置:
1.在虛擬環境中安裝包。
pip install django-tinymce==2.6.0
2.在test6/settings.py中為INSTALLED_APPS添加編輯器應用。
INSTALLED_APPS = ( ... 'tinymce', )
3.在test6/settings.py中添加編輯器配置。
TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'width': 600, 'height': 400, }
4.在test6/urls.py中配置編輯器url。
urlpatterns = [ ... url(r'^tinymce/', include('tinymce.urls')), ]
在后台管理頁面中使用(Admin):
1)在booktest/models.py中,定義模型類,模型類的屬性為HTMLField()類型。
from django.db import models from tinymce.models import HTMLField class GoodsInfo(models.Model): gcontent=HTMLField()
2)生成遷移文件。
python manage.py makemigrations
3)執行遷移。
python manage.py migrate
4)在booktest/admin.py中注冊模型類GoodsInfo
from django.contrib import admin from models import * class GoodsInfoAdmin(admin.ModelAdmin): list_display = ['id'] admin.site.register(GoodsInfo,GoodsInfoAdmin)
5)運行服務器,進入admin后台管理,點擊GoodsInfo的添加,即可看到效果
在編輯器中編輯內容后保存。即可
自定義編輯器:
1)在booktest/views.py中定義視圖editor,用於顯示編輯器。
def editor(request): return render(request, 'booktest/editor.html')
2)在booktest/urls.py中配置url。
url(r'^editor/',views.editor),
3)在項目的目錄創建statics文件夾在該文件的文件夾里面創建js,css,img文件夾並在配置文件setting.py里面添加靜態文件的查找路徑
STATICFILES_DIRS = [os.path.join(BASE_DIRS, 'statics')]
4)打開py_django虛擬環境的目錄,找到tinymce的目錄。
/home/python/.virtualenvs/py_django/lib/python2.7/site-packages/tinymce/static/tiny_mce
5)拷貝tiny_mce.js文件、langs文件夾以及themes文件夾拷貝到項目目錄下的static/js/目錄下。
6)在templates/booktest/目錄下創建editor.html模板。

<head> <meta charset="UTF-8"> <title>editor</title> <script src="/static/js/tiny_mce_src.js"></script> <script> tinymce.init({ 'mode': 'textareas', 'theme': 'advanced', 'width': 500, 'height': 300, }) </script> </head> <body> <form action="/get_content/" method="post"> {% csrf_token %} <textarea name="content" id="" cols="30" rows="10" ></textarea> <input type="submit" value="提交"> </form> </body>
7 )配置url
8)運行服務器,在瀏覽器中輸入如下網址:
http://127.0.0.1:8000
使用已保存的富文本內容
通過富文本編輯器產生的字符串是包含html的:例如:
'<title>展示富文本編輯器內容</title>'
在模板中顯示字符串時,默認會進行html轉義,如果想正常顯示需要關閉轉義。
問:在模板中怎么關閉轉義
方式一:過濾器safe
方式二:標簽autoescape off
使用流程:
1)在booktest/views.py中定義視圖show,用於顯示富文本編輯器的內容。
def show_goods(request): """顯示數據庫當中的內容""" contents = GoodsInfo.objects.get(id=2) return render(request, 'booktest/show_goods.html', {'contents': contents})
2)在booktest/urls.py中配置url。
3)在templates/booktest/目錄下創建show.html模板。
<body> {{ contents.gcontent| safe }} {% autoescape off%} {{ contents.gcontent }} {% endautoescape %} </body>
4)運行服務器,在瀏覽器中輸入如下網址:即可顯示
http://127.0.0.1:8000