图片上传
表字段用ChairFiled
settings:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# 上传图片
UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')
py文件:
import os
from master_ptmag_pro import settings
def uploadfile(img):
f=open(os.path.join(settings.UPLOAD_ROOT,'',img.name),'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
路由:
from master_ptmag_pro.settings import UPLOAD_ROOT
from django.views.static import serve
re_path('^upload/(?P<path>.*)$',serve,{'document_root':UPLOAD_ROOT}),
报错:
[23/May/2019 17:29:17] "GET /upload/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20190521203731.jpg HTTP/1.1" 404 1880
添加没有加 uploadfile(img)
def addgood(request):
if request.method=='POST':
name=request.POST.get('name')
price=request.POST.get('price')
descript=request.POST.get('descript')
img=request.FILES.get('img')
uploadfile(img)
Good.objects.create(name=name,price=price,descript=descript,img='/upload/'+img.name)
return render(request,'addgood.html',locals())