Django之富文本(獲取內容,設置內容方式)
富文本
1、Rich Text Format(RTF)
微軟開發的跨平臺文檔格式,大多數的文字處理軟件都能讀取和保存RTF文檔,其實就是可以添加樣式的文檔,和HTML有很多相似的地方
圖示
2、tinymce插件
安裝插件
pip install django-tinymce
配置插件
使用
后臺管理中
HTMLField
頁面中使用
textarea
3、在后臺管理中使用
配置settings.py文件
INSTALLED_APPS 添加 tinymce 應用INSTALLED_APPS = [ ... # 注冊富文本應用 ’tinymce’,]
添加默認配置
# 以字典形式配置富文本框架tinymce# 作用于管理后臺中的富文本編輯器TINYMCE_DEFAULT_CONFIG = { # 使用高級主題,備選項還有簡單主題 ’theme’: ’advanced’, # ’theme’: ’simple’, # 必須指定富文本編輯器(RTF=rich text format)的寬高 ’width’: 800, ’height’: 600, # 漢化 ’language’: ’zh’, # 自定義常用的固定樣式 ’style_formats’: [ # title=樣式名稱 # styles=自定義css樣式 # inline:xxx = 將加樣式后的文本放在行內元素中顯示 # block:xxx = 將加樣式后的文本放在塊級元素中顯示 {’title’: ’Bold text’, ’inline’: ’b’}, {’title’: ’Red text’, ’inline’: ’span’, ’styles’: {’color’: ’#ff0000’}}, {’title’: ’Red header’, ’block’: ’h1’, ’styles’: {’color’: ’#ff0000’}}, {’title’: ’Example 1’, ’inline’: ’span’, ’classes’: ’example1’}, {’title’: ’Example 2’, ’inline’: ’span’, ’classes’: ’example2’}, {’title’: ’Table styles’}, {’title’: ’Table row 1’, ’selector’: ’tr’, ’classes’: ’tablerow1’} ],}
創建模型類
from tinymce.models import HTMLFieldclass Blog(models.Model): sBlog = HTMLField()
注冊模型
admin.site.register
4、在普通頁面使用
使用文本域盛放內容
<form method=’post’ action=’url’><textarea></textarea></form>
添加腳本
<script src=’/static/tiny_mce/tiny_mce.js’></script> <script> tinyMCE.init({ ’mode’: ’textareas’, ’theme’: ’simple’, ’theme’: ’advanced’, ’width’: 800, ’height’: 600, ’language’: ’zh’, ’style_formats’: [ {’title’: ’Bold text’, ’inline’: ’b’}, {’title’: ’Red text’, ’inline’: ’span’, ’styles’: {’color’: ’#ff0000’}}, {’title’: ’Red header’, ’block’: ’h1’, ’styles’: {’color’: ’#ff0000’}}, {’title’: ’Example 1’, ’inline’: ’span’, ’classes’: ’example1’}, {’title’: ’Example 2’, ’inline’: ’span’, ’classes’: ’example2’}, {’title’: ’Table styles’}, {’title’: ’Table row 1’, ’selector’: ’tr’, ’classes’: ’tablerow1’} ], }) </script>
本質上還是使用html的樣式。
5、利用js獲取富文本內容和設置內容給富文本
//editorId是富文本的idfunction SetTinyMceContent(editorId, content) { //給富文本編輯器設置內容 tinyMCE.getInstanceById(editorId).getBody().innerHTML = content; //獲取富文本編輯器的內容 var con = tinyMCE.getInstanceById(editorId).getBody().innerHTML;}
補充知識:Django中Form的Textarea字段
開始以為是這個樣子:
class BlogForm(forms.Form): title = forms.CharField(required = True) content = forms.Textarea()
查看文檔發現是:
from django import forms class BlogForm(forms.Form): title = forms.CharField(required = True) content = forms.CharField(widget=forms.Textarea)
以上這篇Django之富文本(獲取內容,設置內容方式)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
