iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 20
0
Modern Web

使用 Django 開發網頁系統系列 第 20

[Day 20] html 編輯器 tinyMCE

今天把一些樣式弄一弄

網頁可能要可以自己輸入樣式 像 發布公告 可以選文字大小、位置 段落 等等

之前曾經用過這個 tinyMCE
https://www.tinymce.com/
之前看是free的,現在有了價錢 待釐清

來實作一下,用在商品資訊(description)
在 Item 新增 欄位(description)

TextField() 是字串欄位 不用設定長度

store/model.py

...
    description = models.TextField()
...

一有更改就要執行

python manage.py makemigrations

底下會出現這些訊息,要給預設值

Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> ''

執行 migrate ,就會寫到資料庫了

python manage.py migrate

結果

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, store
Running migrations:
  Applying store.0002_item_description... OK

如果都沒錯 就OK了

如果有錯... 就把 migrations 下的 00* 檔案 都刪掉 跟 datebase 刪掉 從做會比較快
但如果上線了 就有用別的方法了 可能就不要用這個功能 就手動建 欄位 跟 model mapping

forms 沒有 textarea 欄位 ,要用 widget 來客製化
並且給他class

store/forms.py

...
    description = forms.CharField(label='細節', widget=forms.Textarea(attrs={'class': 'tinymceTextarea'}))
...
class Meta:
    fields = ('name', 'category', 'description', 'price', )

selector: 選擇要那些要套用
setup: 解決 chrome 報錯 An invalid form control with name='description' is not focusable.

要寫 js 去 init,剛好上一次用 BS 時有 link jQuery
main/static/main/js/main.js

$(document).ready(function () {
  tinymce.init({
    selector: '.tinymceTextarea', 
    setup: function (editor) {
      editor.on('change', function (e) {
        editor.save();
      });
    }
  });
});

這樣就OK了


上一篇
[Day 19] 樣式 bootstrap
下一篇
[Day 21] bootstrap 結合 forms.py 樣式
系列文
使用 Django 開發網頁系統30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言