后台
def add_shop(request):
user_name = request.session.get('user')
if user_name:
user = User.objects.filter(name=user_name).first()
if request.method == 'POST':
name = request.POST.get('name')
price = request.POST.get('price')
#上传文件
path = request.FILES.get('img')
print(name,price,path)
if not all([name,price,path]):
error = '输入框不能为空!'
return render(request,'add_shop.html',locals())
else: # 如果上传了一个实际的文件对象
file_path = name + '.' + path.name.split('.')[-1] # 取到后缀
file = 'img/' + file_path # 数据库存储的路径了
with open(os.path.join(STATICFILES_DIRS[0],file),'wb') as fp:
fp.write(path.read())
Shop.objects.create(name=name,price=price,img_path=file,user=user)
return redirect('/show_user/')
else:
return redirect('/login/')
return render(request,'add_shop.html')
前台
<img src="/static/{{i.img_path}}"