Django-----上传图片

图片上传操作

# 配置静态文件夹
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# 在 form 表单一定得加   enctype="multipart/form-data"
上传图片导入俩个包
from datetime import datetime
import os
from web.settings import STATICFILES_DIRS


class Addgoods(View):
def get(self,request):
one = Onecate.objects.all()
return render(request,'add_goods.html',locals())
def post(self,request):
cid = request.POST.get('cid')
name = request.POST.get('name')
image_url = request.FILES.get('image_url')
price = request.POST.get('price')
if not all([cid,name,image_url,price]):
mes = '请输入完整信息'
else:

上传图片-------------避免重复增加了时间戳  %Y%m%d%H%M%S%f
image_url_name = datetime.now().strftime("%Y%m%d%H%M%S%f")+image_url.name
打开static的路径配置照片上传的位置,需要在static下面新建一个upload文件夹
f = open(os.path.join(settings.STATICFILES_DIRS[0],'upload',image_url_name),'wb')
二进制流写入图片
for i in image_url.chunks():
f.write(i)
f.close()
two = Twocate(name=name,image_url="/static/upload/"+image_url_name,price=price,onecate_id=cid)
two.save()
return redirect('/tnews_type')
return render(request,'add_goods.html',locals())
posted @ 2020-01-06 11:06  Mr-刘  阅读(88)  评论(0编辑  收藏  举报