Table of contents
(1) Customize the uploaded template code
(2) Use the model to process the uploaded file:
The current test has solved the following two problems, both of which are python version problems
2. Open settings.py and add ueditor to INSTALLED_APPS
4. Open the urls.py file of the django project and add the url routing configuration of ueditor
5. After the above steps are configured, it can basically be used.
1. File upload
upload image
- When Django is processing a file upload, the file data is stored in
request.FILES
- Each key in FILES is the name in <input type="file" name="" />
- Note: FILES will only contain data if the requested method is POST and the submitted <form> has enctype="multipart/form-data".
- Otherwise, FILES will be an empty dictionary-like object
(1) Customize the uploaded template code
<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>
- Custom uploaded view code
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) Use the model to process the uploaded file:
Define the property as models.ImageField type
pic=models.ImageField(upload_to='cars/')
- Note: If the attribute type is ImageField and image processing is used, then the package Pillow needs to be installed
pip install Pillow
- Image storage path
- Create a media folder in the project root directory
- After the picture is uploaded, it will be saved to "/static/media/cars/picture file"
- Open the settings.py file and add the media_root item
MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")
- Using django background management, a file box will appear when encountering an ImageField type attribute to complete the file upload
Two, paging operation
- Django provides some classes to manage data pagination, these classes are located in django/core/paginator.py
Paginator object
- Paginator(list, int): returns the pagination object, the parameter is the list data, the number of pieces of data on each side
Attributes
- count: total number of objects
- num_pages: total number of pages
- page_range: list of page numbers, starting from 1, for example [1, 2, 3, 4]
method
- page(num): The subscript starts with 1, if the provided page number does not exist, an InvalidPage exception is thrown
exception
- InvalidPage: Thrown when an invalid page number is passed to page()
- PageNotAnInteger: Thrown when a value that is not an integer is passed to page()
- EmptyPage: Thrown when a valid value is provided to page(), but there are no objects on that page
Page object
create object
- The page() method of the Paginator object returns a Page object without manual construction
Attributes
- object_list: list of all objects on the current page
- number: the serial number of the current page, starting from 1
- paginator: the Paginator object related to the current page object
method
- has_next(): Return True if there is a next page
- has_previous(): Return True if there is a previous page
- has_other_pages(): returns True if there is a previous or next page
- next_page_number(): returns the page number of the next page, if the next page does not exist, an InvalidPage exception is thrown
- previous_page_number(): Returns the page number of the previous page, if the previous page does not exist, an InvalidPage exception is thrown
- len(): returns the number of objects on the current page
- Iterate page objects: visit each object in the current page
code example
1. Create project mydemo
Create view 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})
configure url
path('pag<int:pIndex>/', views.pagTest, name='pagTest'),
Define template 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>
3. Rich text editor
Django integrates UEditor (packaged into an application) Baidu rich text editor
test environment
- ubuntu 16.04
- python 3.8.2
- django 2.2.14
The current test has solved the following two problems, both of which are python version problems
- 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():
configuration method
1. Download and unzip the ueditor file package and place it in the project. As an application directory
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. Open settings.py and add ueditor to INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myadmin',
'myweb',
'ueditor',
]
3. Check whether the settings.py has set the static static directory. You can refer to the following settings
STATIC_URL = '/static/'
#静态目录
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
4. Open the urls.py file of the django project and add the url routing configuration of ueditor
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. After the above steps are configured, it can basically be used.
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, other issues
Currently using the sister UI template css affects the style of the current editor
修改,/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, watermark function
- The function of automatically adding watermark to uploaded pictures is not enabled by default.
- The function of uploading pictures and adding watermarks needs to install PIL
pip install pillow
- Watermark related settings are at the end of ueconfig.json:
"openWaterMark": false, //是否开启 "waterMarkText": "我的水印\nhttp://xxxxx.com", //水印内容,建议一行文本 "waterMarkFont": "msyhbd.ttf", //字体,中文需要字体支持才不会出错 "waterMarkSize": 15, //字体大小 "waterMarkBottom": 45, //下边距 "waterMarkRight": 155 //右边距