使用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中的每个键为<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}}&nbsp;&nbsp;
{%else%}
<a href="/pag{{pindex}}/">{{pindex}}</a>&nbsp;&nbsp;
{%endif%}
{%endfor%}
</body>
</html>

三、富文本编辑器

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

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

测试环境

  • 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   //右边距

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django是一个高级的Python Web框架,它旨在实现简单快捷的网站开发,并且已经成为Python领域最有影响力的web开发框架之一。\[1\] 它由经验丰富的开发人员构建,鼓励快速开发和清洁、务实的设计。Django负责处理Web开发中的许多繁琐任务,使开发人员能够专注于编写应用程序,而无需重新发明轮子。它是免费且开源的,被官方称为完美主义者的Web框架。\[2\] 要安装Django,您可以按照快速安装指南进行操作。首先,确保您已经安装了Python。然后,可以使用pip命令在命令行中安装Django。例如,在命令行中运行以下命令:pip install django。这将自动下载并安装最新版本的Django。\[1\] 如果您想验证Django是否已被Python识别,可以在Python的shell中输入python。然后,在Python提示符下,尝试导入Django并打印其版本号。如果成功导入并打印出版本号,说明Django已经成功安装并可以被Python识别。\[3\] 对于新手入门Django,官方网站https://www.djangoproject.com/提供了详细的文档和教程,您可以在那里找到有关如何开始使用Django的信息。此外,还有许多在线教程和资源可供学习和探索。\[2\] #### 引用[.reference_title] - *1* *3* [Python开发-Django快速入门](https://blog.csdn.net/huidaoli/article/details/121607251)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [使用Python进行网站页面开发——Django框架介绍与安装](https://blog.csdn.net/weixin_63994459/article/details/125841782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值