富文本编辑器
概念
- 能够设置文字样式的页面成为文本编辑器(带有格式的文本信息)
tinyce 配置:
1.在虚拟环境中安装包。
pip install django-tinymce==2.6.0
2.在test6/settings.py中为INSTALLED_APPS添加编辑器应用。
INSTALLED_APPS = ( ... 'tinymce', )
3.在test6/settings.py中添加编辑器配置。
TINYMCE_DEFAULT_CONFIG = {
'theme': 'advanced',
'width': 600,
'height': 400,
}
4.在test6/urls.py中配置编辑器url。
urlpatterns = [
...
url(r'^tinymce/', include('tinymce.urls')),
]
在后台管理页面中使用(Admin):
1)在booktest/models.py中,定义模型类,模型类的属性为HTMLField()类型。
from django.db import models from tinymce.models import HTMLField class GoodsInfo(models.Model): gcontent=HTMLField()
2)生成迁移文件。
python manage.py makemigrations
3)执行迁移。
python manage.py migrate
4)在booktest/admin.py中注册模型类GoodsInfo
from django.contrib import admin from models import * class GoodsInfoAdmin(admin.ModelAdmin): list_display = ['id'] admin.site.register(GoodsInfo,GoodsInfoAdmin)
5)运行服务器,进入admin后台管理,点击GoodsInfo的添加,即可看到效果
在编辑器中编辑内容后保存。即可
自定义编辑器:
1)在booktest/views.py中定义视图editor,用于显示编辑器。
def editor(request): return render(request, 'booktest/editor.html')
2)在booktest/urls.py中配置url。
url(r'^editor/',views.editor),
3)在项目的目录创建statics文件夹在该文件的文件夹里面创建js,css,img文件夹并在配置文件setting.py里面添加静态文件的查找路径
STATICFILES_DIRS = [os.path.join(BASE_DIRS, 'statics')]
4)打开py_django虚拟环境的目录,找到tinymce的目录。
/home/python/.virtualenvs/py_django/lib/python2.7/site-packages/tinymce/static/tiny_mce
5)拷贝tiny_mce.js文件、langs文件夹以及themes文件夹拷贝到项目目录下的static/js/目录下。
6)在templates/booktest/目录下创建editor.html模板。
<head>
<meta charset="UTF-8">
<title>editor</title>
<script src="/static/js/tiny_mce_src.js"></script>
<script>
tinymce.init({
'mode': 'textareas',
'theme': 'advanced',
'width': 500,
'height': 300,
})
</script>
</head>
<body>
<form action="/get_content/" method="post">
{% csrf_token %}
<textarea name="content" id="" cols="30" rows="10" ></textarea>
<input type="submit" value="提交">
</form>
</body>
7 )配置url
8)运行服务器,在浏览器中输入如下网址:
http://127.0.0.1:8000
使用已保存的富文本内容
通过富文本编辑器产生的字符串是包含html的:例如:
'<title>展示富文本编辑器内容</title>'
在模板中显示字符串时,默认会进行html转义,如果想正常显示需要关闭转义。
问:在模板中怎么关闭转义
方式一:过滤器safe
方式二:标签autoescape off
使用流程:
1)在booktest/views.py中定义视图show,用于显示富文本编辑器的内容。
def show_goods(request):
"""显示数据库当中的内容"""
contents = GoodsInfo.objects.get(id=2)
return render(request, 'booktest/show_goods.html', {'contents': contents})
2)在booktest/urls.py中配置url。
3)在templates/booktest/目录下创建show.html模板。
<body>
{{ contents.gcontent| safe }}
{% autoescape off%}
{{ contents.gcontent }}
{% endautoescape %}
</body>
4)运行服务器,在浏览器中输入如下网址:即可显示
http://127.0.0.1:8000
