目录
1,下载解压ueditor文件包,放置在项目中.,作为一个应用目录
2,打开settings.py,给INSTALLED_APPS加入应用ueditor
3,检查一下settings.py是否设置好static静态目录,可参考如下设置
4,打开django项目的urls.py文件,添加ueditor的url路由配置
一、文件上传
上传图片
- 当Django在处理文件上传的时候,文件数据被保存在
request.FILES
- FILES中的每个键为<input type="file" name="" />中的name
- 注意:FILES只有在请求的方法为POST 且提交的<form>带有enctype="multipart/form-data" 的情况下才会包含数据。
- 否则,FILES 将为一个空的类似于字典的对象
(1) 自定义上传的模板代码
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="post" action="upload/" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="pic"/><br>
<input type="submit" value="上传">
</form>
</body>
</html>
- 自定义上传的视图代码
from django.shortcuts import render
from django.http import HttpResponse
from PIL import Image
import time,os
def upload(request):
'''执行图片的上传'''
myfile = request.FILES.get("mypic",None)
if not myfile:
return HttpResponse("没有上传文件信息")
filename = str(time.time())+"."+myfile.name.split('.').pop()
destination = open("./static/pics/"+filename,"wb+")
for chunk in myfile.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
# 执行图片缩放
im = Image.open("./static/pics/"+filename)
# 缩放到75*75(缩放后的宽高比例不变):
im.thumbnail((75, 75))
# 把缩放后的图像用jpeg格式保存:
im.save("./static/pics/s_"+filename,None)
#执行图片删除
#os.remove("./static/pics/"+filename)
return HttpResponse("上传成功!图片:"+filename)
(2) 使用模型处理上传文件:
将属性定义成models.ImageField类型
pic=models.ImageField(upload_to='cars/')
- 注意:如果属性类型为ImageField获使用图片处理,那么就需要安装包Pillow
pip install Pillow
- 图片存储路径
- 在项目根目录下创建media文件夹
- 图片上传后,会被保存到“/static/media/cars/图片文件”
- 打开settings.py文件,增加media_root项
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
- 使用django后台管理,遇到ImageField类型的属性会出现一个file框,完成文件上传
二、分页操作
- Django提供了一些类实现管理数据分页,这些类位于django/core/paginator.py中
Paginator对象
- Paginator(列表,int):返回分页对象,参数为列表数据,每面数据的条数
属性
- count:对象总数
- num_pages:页面总数
- page_range:页码列表,从1开始,例如[1, 2, 3, 4]
方法
- page(num):下标以1开始,如果提供的页码不存在,抛出InvalidPage异常
异常exception
- InvalidPage:当向page()传入一个无效的页码时抛出
- PageNotAnInteger:当向page()传入一个不是整数的值时抛出
- EmptyPage:当向page()提供一个有效值,但是那个页面上没有任何对象时抛出
Page对象
创建对象
- Paginator对象的page()方法返回Page对象,不需要手动构造
属性
- object_list:当前页上所有对象的列表
- number:当前页的序号,从1开始
- paginator:当前page对象相关的Paginator对象
方法
- has_next():如果有下一页返回True
- has_previous():如果有上一页返回True
- has_other_pages():如果有上一页或下一页返回True
- next_page_number():返回下一页的页码,如果下一页不存在,抛出InvalidPage异常
- previous_page_number():返回上一页的页码,如果上一页不存在,抛出InvalidPage异常
- len():返回当前页面对象的个数
- 迭代页面对象:访问当前页面中的每个对象
代码示例
1. 创建项目mydemo
创建视图pagTest
from django.core.paginator import Paginator
def pagTest(request, pIndex):
list1 = AreaInfo.objects.filter(aParent__isnull=True)
p = Paginator(list1, 10)
if pIndex == '':
pIndex = '1'
pIndex = int(pIndex)
list2 = p.page(pIndex)
plist = p.page_range
return render(request, 'booktest/pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})
配置url
path('pag<int:pIndex>/', views.pagTest, name='pagTest'),
定义模板pagTest.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
{%for area in list%}
<li>{
{area.id}}--{
{area.atitle}}</li>
{%endfor%}
</ul>
{%for pindex in plist%}
{%if pIndex == pindex%}
{
{pindex}}
{%else%}
<a href="/pag{
{pindex}}/">{
{pindex}}</a>
{%endif%}
{%endfor%}
</body>
</html>
三、富文本编辑器
Django集成UEditor (封装成应用) 百度富文本编辑器
测试环境
- ubuntu 16.04
- python 3.8.2
- django 2.2.14
目前测试解决了出现的以下两个问题,都是python版本问题
- error1
# name 'file' is not defined
controller.py 68行
# jsonfile = file(config_path)
jsonfile = open(config_path)
- error2
File "/home/yc/py6/myproject-test/ueditor/controller.py", line 45,
in buildFileName
for key, value in texts.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'
controller.py 45行
# for key, value in texts.iteritems():
for key, value in texts.items():
配置方法
1,下载解压ueditor文件包,放置在项目中.,作为一个应用目录
myproject:
manage.py myproject static ueditor
myadmin myweb templates
uediter文件夹包括以下:
controller.py __init__.py msyhbd.ttf UE/ urls.py
controller.pyc __init__.pyc __pycache__ ueconfig.json urls.pyc
2,打开settings.py,给INSTALLED_APPS加入应用ueditor
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myadmin',
'myweb',
'ueditor',
]
3,检查一下settings.py是否设置好static静态目录,可参考如下设置
STATIC_URL = '/static/'
#静态目录
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
4,打开django项目的urls.py文件,添加ueditor的url路由配置
myproject/myproject/urls.py:
from django.urls import include,path
from django.contrib import admin
urlpatterns = [
path('ueditor/', include('ueditor.urls')),
path('admin/',include('myadmin.urls')),
path('',include('myweb.urls')),
]
5,上面步骤配置完成之后,基本可以使用了。
ueditor配置可能需要根据你的项目具体情况修改。
ueditor前端配置文件,在ueditor/UE/ueditor.config.js
ueditor后端配置文件,在ueditor/ueconfig.json 具体配置可参考ueditor官网
此时可以在需要使用富文本编辑器的位置设置一下代码:
html:
<link rel="stylesheet" type="text/css" href="/ueditor/UE/third-party/SyntaxHighlighter/shCoreDefault.css">
<script type="text/javascript" src="/ueditor/UE/third-party/SyntaxHighlighter/shCore.js"></script>
<script type="text/javascript" src="/ueditor/UE/ueditor.config.js"></script>
<script type="text/javascript" src="/ueditor/UE/ueditor.all.min.js"></script>
<script type="text/javascript" src="/ueditor/UE/lang/zh-cn/zh-cn.js"></script>
<div class="am-form-group">
<label for="user-intro" class="am-u-sm-3 am-form-label">商品简介</label>
<div class="am-u-sm-9">
<!-- <textarea name="descr" class="" rows="10" id="user-intro" placeholder="请输入商品简介"></textarea> -->
<!-- <script id="editor" type="text/plain" style="width:100%;height:500px;"></script> -->
<script id="editor" name="content" type="text/plain" style="height:500px;"></script>
</div>
</div>
<script type="text/javascript">
var ue = UE.getEditor('editor');
SyntaxHighlighter.all();
</script>
6,其它问题
当前使用 妹子UI 模板 css影响了当前的编辑器的样式
修改,/static/myadmin/assets/css/app.css 379行
.tpl-content-wrapper {
transition: all 0.4s ease-in-out;
/*position: relative;*/
margin-left: 240px;
z-index: 1101;
min-height: 922px;
border-bottom-left-radius: 3px;
}
7,水印功能
- 上传图片自动加水印 该功能默认没开启。
- 上传图片加水印功能需要安装PIL
pip install pillow
- 水印相关设置在ueconfig.json末尾:
"openWaterMark": false, //是否开启 "waterMarkText": "我的水印\nhttp://xxxxx.com", //水印内容,建议一行文本 "waterMarkFont": "msyhbd.ttf", //字体,中文需要字体支持才不会出错 "waterMarkSize": 15, //字体大小 "waterMarkBottom": 45, //下边距 "waterMarkRight": 155 //右边距