的安裝和在
Django Ueditor
頁面的使用請看,接下來的内容是基于這篇文章的環境進行的:如何使用 Django Ueditor,如果你按照下面的流程來做還有關于
admin
的報錯,很有可能是沒有裝好環境。。
Ueditor
總體流程
以文章模型為例
1、建立文章模型
2、建立該文章模型的Form
3、寫個html界面
4、寫個視圖函數article(),并提供這個Form給前端渲染
5、寫個路由,并配置好settings.py檔案
具體實作過程
在app中:
1、建立文章模型
from DjangoUeditor3.DjangoUeditor.models import UEditorField
class Article(models.Model):
title = models.CharField('标題', max_length=100)
content = UEditorField('内容', width=1000, height=500, toolbars="besttome")
# 這裡不一定要用UEditorField,可以用TextField,這個對非admin界面來說無關緊要哈。
def __str__(self):
return self.title
然後資料遷移(如果報錯,則請看上一篇文章):
python manage.py makemigrations
python manage.py migrate
2、建立forms.py并建立該文章模型的Form
在這裡我隻對該文章模型的富文本字段建立Form,友善前端個性化設計:
from django.forms import forms
from DjangoUeditor.forms import UEditorField
class ContentForm(forms.Form):
content = UEditorField("", height=500, width=830, toolbars='besttome')
拓展:這個toolbars有幾種值:mini、normal、full、besttome,自己根據喜好使用哈,官方也提供了文檔自己設計工具欄。
3、寫個HTML界面:
<!DOCTYPE html>
<html >
<head>
<title>寫文章</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{{ content_form.media }}
<!-- 注意!這裡引入樣式:{{ content_form.media }} -->
</head>
<body>
<form action="{% url 'article' %}" method="post">
{% csrf_token %}
<label for="title">文章标題</label>
<input type="text" id="title" name="title" value="" required/>
<!-- 關鍵 -->
<label for="id_content">文章内容</label>
{{ content_form }}
<!-- 關鍵 -->
<button type="submit">儲存</button>
</form>
</body>
</html>
注意!這裡引入了樣式:
{{ content_form.media }}
4、寫個view
from django.http import HttpResponseRedirect
from django.shortcuts import render
from app.forms import ContentForm
from app.models import Article
def article(request):
context = {
'content_form': ContentForm()
}
if request.method == 'GET': # 擷取空界面用于建立該文章的内容
return render(request, 'app/article.html', context=context)
if request.method == 'POST': # 建立文章
Article.objects.create(**request.POST)
return HttpResponseRedirect('在送出後一般的做法是前往文章清單頁展示新文章')
在全局配置檔案夾中:
1、寫個路由
簡單起見,我就不在app中建立urls.py了,直接在主urls.py中寫上下面的路由。
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from app1.views import article
urlpatterns = [
...
path('article/', article, name='article'),
]
# 加入下面這個是為了使富文本可以上傳圖檔視訊等檔案
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
2、在settings.py中添加:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# 加入下面這個是為了使富文本可以上傳圖檔視訊等檔案
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
至此,大功告成。
再給你看看效果圖和項目目錄結構:
效果圖:
項目目錄結構:
下一篇:Django Ueditor之原樣展示已有的富文本内容到富文本編輯器
對了,我有個微信公衆号你要不要看一看?我連二維碼都給你準備好了: