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 。在模板中定义上传表单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单内容</title>
</head> 
<body>
    <form method="post" action="/handleimage/" enctype="multipart/form-data"> 
    {% csrf_token %} 
    <input type="file" name="image"><br> 
    <input type="submit" value="提交"> 
    </form> 
</body> 
</html>

 

④打开 student/views.py 文件,创建 handle() 视图函数,用于接收表单保存图片。 request 对象的 FILES 属性用 于接收请求的文件,包括图片内容。
request.FILES.get(name)
通过 <input> 标签的 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
<!DOCTYPE html> 
<html lang="en"> 
<head>
    <meta charset="UTF-8"> 
    <title>批量显示图片</title> 
</head> 
<body>
    {% for picture in picturelist %} 
        <img src="/static/media/{{ picture.picture }}" width="200px" height="150px"> 
    {% endfor %} 
</body> 
</html>
运行服务器,点击编译器控制台中的如下网址http://127.0.0.1:8000,登陆后添加/show/,
即http://127.0.0.1:8000/show/
即可查看刚刚上传的图片一起显示了。

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值