1. 程式人生 > >轉:Django使用Djangoueditor富文字編輯器

轉:Django使用Djangoueditor富文字編輯器

Django使用Djangoueditor富文字編輯器

——————————————————————————————————————

第一步:

- 下載Djangoueditor壓縮包,將包解壓放到專案目錄資料夾下

- 下載地址:https://github.com/zhangfisher/DjangoUeditor

第二步:

- Python安裝DjangoUeditor: pip install DjangoUeditor

第三步:

配置檔案settings.py中註冊DjangoUeditor

程式碼:

INSTALLED_APPS = (     'django.contrib.admin',     'django.contrib.auth',     'django.contrib.contenttypes',     'django.contrib.sessions',     'django.contrib.messages',     'django.contrib.staticfiles',     'app01',     'tinymce',     'DjangoUeditor', )

第四步:

配置DjangoUeditor相對應的url,在專案的主url檔案中新增

程式碼:

urlpatterns = [     url(r'^admin/', include(admin.site.urls)),     url(r'^ueditor/', include('DjangoUeditor.urls')), ]

第五步(後臺使用):django自帶後臺admin使用

程式碼:

from DjangoUeditor.models import UEditorField

class News(models.Model):

    newscontent_djueditor = UEditorField(         u'內容', height=100, width=500, default='test',         toolbars='full'

    )

注意:DjangoUeditor需要使用到media路徑的配置******(這個很重要)******

MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_DIRS = (     os.path.join(BASE_DIR, 'media')

)

第六步:

以上步驟實現完成後進入到django後臺頁面找到對應的表新增內容就能看到相應的djangoueditor編輯器的頁面直接進行操作;

第七步(自建後臺頁面):我這裡使用的是django的表單不是html的表單

程式碼:

from DjangoUeditor.forms import UEditorField class DjangoueditorForm(forms.Form):     content = UEditorField(         "", initial="", width=800, height=200,         toolbars='mini',         imagePath='ueimages/',  # 上傳圖片儲存的路徑,不設定的話預設是配置檔案中MEDIA_ROOT路徑         filePath='files_ue/'

    )

第八步(檢視函式中新增業務邏輯):

程式碼:

@csrf_exempt def addnews(request, nid):     forms = DjangoueditorForm()     return render(request, 'app01/addnews.html', {'forms': forms})

第九步(前端頁面業務邏輯):

程式碼:

{% block forms_style %}

    {{ forms.media }}  {# 這裡是載入djangoueditor相關的js、css檔案,否則頁面不顯示富文字編輯器 #} {% endblock %}

<form action="" method="post">

<div class="formRow">     <label>內容:</label>     <div class="formRight">         {{ forms }}     </div>     <div class="clear"></div>

</div>

</form>

第十步:上傳圖片和檔案後富文字編輯器Djangoueditor中圖片和檔案不顯示的原因

程式碼:

# 新增配置檔案這裡如果不新增圖片和檔案不顯示

MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_DIRS = (     os.path.join(BASE_DIR, 'media')

)