Django富文字編輯器
阿新 • • 發佈:2019-01-13
Django富文字編輯器
在django模型中,如果將商品詳情欄位型別設定為TextFiled(),當將該模型加入到後臺管理的時候,只會呈現出普通的文字框。但是,我們實際工作中,編輯商品詳情需要進行格式的編輯、上傳圖片、排版、修改文字顏色,這些普通的TextField都是不能實現的。
怎麼解決?使用富文字編輯器
富文字編輯器有很多種類,我們專案中採用ckeditor
文件地址:https://pypi.org/project/django-ckeditor/
文件中非常詳細,具體參考文件,以下是簡單入門步驟:
在您的python路徑中安裝或新增django-ckeditor。
pip install django- ckeditor
將ckeditor新增到您的INSTALLED_APPS設定中。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sp_user.apps.SpUserConfig', # 使用者模組
'sp_goods.apps.SpGoodsConfig' , # 商品模組
'ckeditor', # 新增ckeditor富文字編輯器
]
配置靜態檔案路徑
看文件:https://docs.djangoproject.com/en/dev/howto/static-files/
刪除之前配置的STATICFILES_DIRS(本來上線就要刪除),修改為STATIC_ROOT
#STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
#]
# 設定靜態檔案根目錄 上線的時候使用
STATIC_ROOT = os.path.join(BASE_DIR, "static" )
使用以下命令,將django中安裝在INSTALLED_APPS的其他應用所有的靜態檔案收集到STATIC_ROOT指定目錄下
python.exe manage.py collectstatic
這個時候 我們在 static 目錄下就能看的 ckeditor 目錄,裡面就是ckeditor使用到的所有的靜態檔案(css,js,image)。
這個時候又將之前的修改改回去,現在還沒有上線,還得用之前的配置。
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
# 設定靜態檔案根目錄 上線的時候使用
# STATIC_ROOT = os.path.join(BASE_DIR, "static")
設定ckeditor的上傳目錄
這個目錄是相對目錄,相對與 MEDIA_ROOT
CKEDITOR_UPLOAD_PATH = "uploads/"
將ckeditor_uploader新增到您的INSTALLED_APPS設定中。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sp_user.apps.SpUserConfig', # 使用者模組
'sp_goods.apps.SpGoodsConfig', # 商品模組
'ckeditor', # 新增ckeditor富文字編輯器
'ckeditor_uploader', # 新增ckeditor富文字編輯器檔案上傳部件
]
在主路由中配置 ckeditor 上傳檔案使用到的url地址
ckeditor上傳檔案內部機制使用 ajax 非同步上傳檔案,需要配置上傳訪問地址才能被訪問到。
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 上傳部件自動呼叫的上傳地址
url(r'^ckeditor/', include("ckeditor_uploader.urls")),
# 使用者模組
url(r'^user/', include("sp_user.urls", namespace="sp_user")),
# 其他模組
]
安裝pillow(已經安裝的不用重複安裝)
ckeditor上傳檔案使用pillow
設定ckeditor在後臺顯示的樣式(顯示效果)
使用預設配置就行,具體看文件修改
# 編輯器樣式配置
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
},
}
將商品SPU表的詳情欄位修改RichTextUploadingField,使用ckeditor為們單獨提供的欄位型別,修改完後,後臺自動顯示富文字編輯器樣式,可以上傳圖片
# 匯入ckeditor上富文字編輯器自帶欄位
from ckeditor_uploader.fields import RichTextUploadingField
class GoodsSPU(BaseModel):
"""
商品SPU表
"""
spu_name = models.CharField(verbose_name='商品SPU名稱',
max_length=20,
)
# 使用ckeditor為我們提供的欄位,不用重新遷移就可以
content = RichTextUploadingField(verbose_name="商品詳情")
def __str__(self):
return self.spu_name
class Meta:
verbose_name = "商品SPU"
verbose_name_plural = verbose_name
前臺模板顯示
{{content|safe}}