栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django之自定义 form 表单上传图片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django之自定义 form 表单上传图片

创建一个名为 studenttest 的项目与一个名为 student 的应用程序
django-admin startproject studenttest  

python manage.py startapp student
打开 student/views.py 文件,创建 uploadimage() 视图函数
def uploadimage(request): 
    return render(request,"student/file.html")
打开 student/urls.py 文件,配置 url(注意这个最后面的,要记得添加,养成良好习惯)
url(r"^file/$",views.uploadimage),
在 templates/student/ 目录下创建模板 file.html 。在模板中定义上传表单



    
    表单内容
 

    
{% csrf_token %}

 

④打开 student/views.py 文件,创建 handle() 视图函数,用于接收表单保存图片。 request 对象的 FILES 属性用 于接收请求的文件,包括图片内容。
request.FILES.get(name) 通过 标签的 name 属性值获得图片对象。
对象 .chunks() 返回图片对象的数据值,类型为生成器对象。若要获取所有数据内容,则需要进行 遍历处理。
对象 .name 返回图片对象的文件名。
对象 .file 获取的二进制数据
配置handle() 视图函数的代码:
from django.conf import settings 
from django.http import HttpResponse 
from .models import PictrueInfo
def handle(request):
    image = request.FILES.get("image") 
    # 图片名 
    image_name = image.name 
    # 图片内容 
    image_content = image.chunks() 
    # 写入文件 
    path = "%s/student/%s"%(settings.MEDIA_ROOT,image_name)
    with open(path,"wb") as fs: 
        for temp in image_content: 
            fs.write(temp)
    # 图片路径名写入数据库 
    PictrueInfo.objects.create(picture="student/%s"%image_name) 
    return HttpResponse("OK")
打开 student/urls.py 文件,配置 url
url(r"^handleimage/$",views.handle),

运行服务器,在浏览器中(注:当选择文件后点击按钮上传图片即可)输入如下网址:         

http://127.0.0.1:8000/file/

当然127.0.0.1也可以换成localhost

可在pycharm中的项目中检查图片是否上传成功  media>>student

接下来是在网页中显示图片,打开 student/views.py 文件,创建 showpic()视图函数

# 批量显示图片 
def showpic(request): 
    picturelist = PictrueInfo.objects.all() 
    return render(request,"student/picture.html",{"picturelist":picturelist})
需要提醒的是,每操作完一个视图函数,都需要修改相应的url配置 打开 student/urls.py 文件,配置 url
url(r"^show/$",views.showpic),
在 templates/student/ 目录下创建模板 picture.html
 
 

     
    批量显示图片 
 

    {% for picture in picturelist %} 
        { picture.picture }}" width="200px" height="150px"> 
    {% endfor %} 
 
运行服务器,点击编译器控制台中的如下网址http://127.0.0.1:8000,登陆后添加/show/, 即http://127.0.0.1:8000/show/ 即可查看刚刚上传的图片一起显示了。

以上就是Django框架的一个小应用,有兴趣的朋友可以自行操作。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/664896.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号