• 使用Python进行页面开发——Django常用Web工具


    目录

    一、文件上传

    上传图片

    (1) 自定义上传的模板代码

    (2) 使用模型处理上传文件:

    二、分页操作

    Paginator对象

    Page对象

    代码示例

    三、富文本编辑器

    目前测试解决了出现的以下两个问题,都是python版本问题

    配置方法

    1,下载解压ueditor文件包,放置在项目中.,作为一个应用目录

    2,打开settings.py,给INSTALLED_APPS加入应用ueditor

    3,检查一下settings.py是否设置好static静态目录,可参考如下设置

    4,打开django项目的urls.py文件,添加ueditor的url路由配置

    5,上面步骤配置完成之后,基本可以使用了。

    6,其它问题

    7,水印功能


    一、文件上传

    上传图片

    • 当Django在处理文件上传的时候,文件数据被保存在request.FILES
    • FILES中的每个键为中的name
    • 注意:FILES只有在请求的方法为POST 且提交的
      带有enctype="multipart/form-data" 的情况下才会包含数据。
    • 否则,FILES 将为一个空的类似于字典的对象

    (1) 自定义上传的模板代码

    1. <html>
    2. <head>
    3. <title>文件上传title>
    4. head>
    5. <body>
    6. <form method="post" action="upload/" enctype="multipart/form-data">
    7. <input type="text" name="title"><br>
    8. <input type="file" name="pic"/><br>
    9. <input type="submit" value="上传">
    10. form>
    11. body>
    12. html>
    • 自定义上传的视图代码
    1. from django.shortcuts import render
    2. from django.http import HttpResponse
    3. from PIL import Image
    4. import time,os
    5. def upload(request):
    6. '''执行图片的上传'''
    7. myfile = request.FILES.get("mypic",None)
    8. if not myfile:
    9. return HttpResponse("没有上传文件信息")
    10. filename = str(time.time())+"."+myfile.name.split('.').pop()
    11. destination = open("./static/pics/"+filename,"wb+")
    12. for chunk in myfile.chunks(): # 分块写入文件
    13. destination.write(chunk)
    14. destination.close()
    15. # 执行图片缩放
    16. im = Image.open("./static/pics/"+filename)
    17. # 缩放到75*75(缩放后的宽高比例不变):
    18. im.thumbnail((75, 75))
    19. # 把缩放后的图像用jpeg格式保存:
    20. im.save("./static/pics/s_"+filename,None)
    21. #执行图片删除
    22. #os.remove("./static/pics/"+filename)
    23. 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

    1. from django.core.paginator import Paginator
    2. def pagTest(request, pIndex):
    3. list1 = AreaInfo.objects.filter(aParent__isnull=True)
    4. p = Paginator(list1, 10)
    5. if pIndex == '':
    6. pIndex = '1'
    7. pIndex = int(pIndex)
    8. list2 = p.page(pIndex)
    9. plist = p.page_range
    10. return render(request, 'booktest/pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})

    配置url

    path('pag/', views.pagTest, name='pagTest'),
    

    定义模板pagTest.html

    1. html>
    2. <html>
    3. <head>
    4. <title>title>
    5. head>
    6. <body>
    7. <ul>
    8. {%for area in list%}
    9. <li>{{area.id}}--{{area.atitle}}li>
    10. {%endfor%}
    11. ul>
    12. {%for pindex in plist%}
    13. {%if pIndex == pindex%}
    14. {{pindex}}  
    15. {%else%}
    16. <a href="/pag{{pindex}}/">{{pindex}}a>  
    17. {%endif%}
    18. {%endfor%}
    19. body>
    20. html>

    三、富文本编辑器

    Django集成UEditor (封装成应用) 百度富文本编辑器

    http://ueditor.baidu.com/website/

    测试环境

    • ubuntu 16.04
    • python 3.8.2
    • django 2.2.14

    目前测试解决了出现的以下两个问题,都是python版本问题

    • error1
    1. # name 'file' is not defined
    2. controller.py 68
    3. # jsonfile = file(config_path)
    4. jsonfile = open(config_path)
    • error2
    1. File "/home/yc/py6/myproject-test/ueditor/controller.py", line 45,
    2. in buildFileName
    3. for key, value in texts.iteritems():
    4. AttributeError: 'dict' object has no attribute 'iteritems'
    5. controller.py 45
    6. # for key, value in texts.iteritems():
    7. for key, value in texts.items():

    配置方法

    1,下载解压ueditor文件包,放置在项目中.,作为一个应用目录

    1. myproject:
    2. manage.py myproject static ueditor
    3. myadmin myweb templates
    4. uediter文件夹包括以下:
    5. controller.py __init__.py msyhbd.ttf UE/ urls.py
    6. controller.pyc __init__.pyc __pycache__ ueconfig.json urls.pyc

    2,打开settings.py,给INSTALLED_APPS加入应用ueditor

    1. INSTALLED_APPS = [
    2. 'django.contrib.admin',
    3. 'django.contrib.auth',
    4. 'django.contrib.contenttypes',
    5. 'django.contrib.sessions',
    6. 'django.contrib.messages',
    7. 'django.contrib.staticfiles',
    8. 'myadmin',
    9. 'myweb',
    10. 'ueditor',
    11. ]

    3,检查一下settings.py是否设置好static静态目录,可参考如下设置

    1. STATIC_URL = '/static/'
    2. #静态目录
    3. STATICFILES_DIRS = (
    4. os.path.join(BASE_DIR, "static"),
    5. )

    4,打开django项目的urls.py文件,添加ueditor的url路由配置

    1. myproject/myproject/urls.py:
    2. from django.urls import include,path
    3. from django.contrib import admin
    4. urlpatterns = [
    5. path('ueditor/', include('ueditor.urls')),
    6. path('admin/',include('myadmin.urls')),
    7. path('',include('myweb.urls')),
    8. ]

    5,上面步骤配置完成之后,基本可以使用了。

    1. ueditor配置可能需要根据你的项目具体情况修改。
    2. ueditor前端配置文件,在ueditor/UE/ueditor.config.js
    3. ueditor后端配置文件,在ueditor/ueconfig.json 具体配置可参考ueditor官网
    4. 此时可以在需要使用富文本编辑器的位置设置一下代码:
    5. html:
    6. <link rel="stylesheet" type="text/css" href="/ueditor/UE/third-party/SyntaxHighlighter/shCoreDefault.css">
    7. <script type="text/javascript" src="/ueditor/UE/third-party/SyntaxHighlighter/shCore.js">script>
    8. <script type="text/javascript" src="/ueditor/UE/ueditor.config.js">script>
    9. <script type="text/javascript" src="/ueditor/UE/ueditor.all.min.js">script>
    10. <script type="text/javascript" src="/ueditor/UE/lang/zh-cn/zh-cn.js">script>
    11. <div class="am-form-group">
    12. <label for="user-intro" class="am-u-sm-3 am-form-label">商品简介label>
    13. <div class="am-u-sm-9">
    14. <script id="editor" name="content" type="text/plain" style="height:500px;">script>
    15. div>
    16. div>
    17. <script type="text/javascript">
    18. var ue = UE.getEditor('editor');
    19. SyntaxHighlighter.all();
    20. script>

    6,其它问题

    当前使用 妹子UI 模板 css影响了当前的编辑器的样式

    1. 修改,/static/myadmin/assets/css/app.css 379
    2. .tpl-content-wrapper {
    3. transition: all 0.4s ease-in-out;
    4. /*position: relative;*/
    5. margin-left: 240px;
    6. z-index: 1101;
    7. min-height: 922px;
    8. border-bottom-left-radius: 3px;
    9. }

    7,水印功能

    • 上传图片自动加水印 该功能默认没开启。
    • 上传图片加水印功能需要安装PIL
      pip install pillow
      
    • 水印相关设置在ueconfig.json末尾:
      1. "openWaterMark": false, //是否开启
      2. "waterMarkText": "我的水印\nhttp://xxxxx.com", //水印内容,建议一行文本
      3. "waterMarkFont": "msyhbd.ttf", //字体,中文需要字体支持才不会出错
      4. "waterMarkSize": 15, //字体大小
      5. "waterMarkBottom": 45, //下边距
      6. "waterMarkRight": 155 //右边距

     

     

  • 相关阅读:
    什么是代码签名证书?
    如果刷新网页或者下拉出现白屏可能是什么原因以及url相关问题
    读取excel数据的方式整理
    Linux | 从虚拟地址到物理地址
    Eureka的Ribbon负载均衡
    目标检测YOLO实战应用案例100讲-高速铁路供电安全检测监测系统图像智能识别
    浅识java多线程
    OSG嵌入QT的简明总结2
    Git推送和拉取Github
    【iOS开发--Swift语法】gard 的具体使用
  • 原文地址:https://blog.csdn.net/weixin_63994459/article/details/126142008