Django version == 1.9.5
python == 2.7
首先需要在settings.py里设置media:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media").replace('\\','/')
models:
classphoto(models.Model):
owner = models.ForeignKey(User,verbose_name='上传者')
image= models.ImageField(upload_to='photos/',blank=True,null=True)
def__unicode__(self):
return'%s %s'%(self.owner,self.image)
form.py
classphotoForm(forms.Form):
image = forms.ImageField(required=False)
views:
def upload_image(request):
if request.method == 'POST':
form = photoForm(request.POST,request.FILES)
if form.is_valid():
#判断是否上传了文件
if 'docfile' in request.FILES:
image = request.FILES["docfile"]
#修改文件名字
image.name = str(request.user)+str(time)+'.jpg'
s=photo(owner=request.user,image=image)
s.save()
return HttpResponse('上传成功')
else:
#没有上传文件直接点了上传就重定向到上传页面
return redirect('/upload/')
else:
image = None
return HttpResponse('上传失败')
else:
return render(request,'upload_image.html')
编辑上传模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
<fieldset>
<legend>上传文件</legend>
<input type="file" name="docfile" />
<input type="submit" value="上传"/>
</fieldset>
</form>
</body>
</html>
最后是url:
url(r'^upload/','upload.views.upload_image',name='upload_image'),
图片上传到此完成