django富文本编辑器

时间:2023-01-03 05:14:23

-------------------tinymce富文本编辑器
1、下载安装
1、在网站pypi网站搜索并下载"django-tinymce-2.4.0"

2、解压:tar zxvf django-tinymce-2.4.0.tar.gz

3、进入解压后的目录,工作在虚拟环境,安装:
python setup.py install

2、应用到项目
1、在settings.py中为INSTALLED_APPS添加编辑器应用
INSTALLED_APPS = (
...
'tinymce',
)

2、在settings.py中添加编辑配置项
TINYMCE_DEFAULT_CONFIG = {
'theme': 'advanced',
'width': 600,
'height': 400,
}

3、在根urls.py中配置
urlpatterns = [
...
url(r'^tinymce/', include('tinymce.urls')),
]

4、在应用中定义模型的属性
from django.db import models
from tinymce.models import HTMLField

class GoodInfo(models.Model):
...
gdetail = HTMLField()

3、自定义使用
1、定义视图editor,用于显示编辑器并完成提交
def editor(request):
return render(request, 'other/editor.html')

2、配置url
urlpatterns = [
...
url(r'^editor/$', views.editor, name='editor'),
]

3、创建模板editor.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src='/static/tiny_mce/tiny_mce.js'></script>
<script type="text/javascript">
tinyMCE.init({
'mode':'textareas',
'theme':'advanced',
'width':400,
'height':100
});
</script>
</head>
<body>
<form method="post" action="/detail/">
<input type="text" name="hname">
<br>
<textarea name='gdetail'>这是一个富文本编辑器</textarea>
<br>
<input type="submit" value="提交">
</form>
</body>
</html>

4、定义视图detail,接收请求,并更新goodInfo对象
def detail(request):
hname = request.POST['hname']
gdetail = request.POST['gdetail']

goodinfo = GoodInfo.objects.get(pk=1)
goodinfo.hname = hname
goodinfo.gdetail = gdetail
goodinfo.save()

return render(request, 'other/detail.html', {'goods': goodinfo})

5、添加url项
urlpatterns = [
...
url(r'^detail/$', views.detail, name='detail'),
]

6、定义模板detail.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
姓名:{{goods.gname}}
<hr>
{%autoescape off%}
{{goods.gdetail}}
{%endautoescape%}
</body>
</html>