由于图片上传的需要,学习了一波上传
1. 上传
前端代码
<form action="写上相应的定向位置" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="btn_file" name="pic1" />
<br/>
<input type="submit" value="确定" />
</form>
后台代码
def add_image(request):
if request.method == "POST":
picture = request.FILES[‘pic1‘]
fname = ‘%s\\pictures\\%s‘ % (settings.MEDIA_ROOT, picture.name)
with open(fname, ‘wb‘) as pic:
for c in picture.chunks():
pic.write(c)
return HttpResponse("ok")
else:
return HttpResponse("error")
其中有一部分用到了settings中的设置(整个项目的settings)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, "media")
这样 图片上传便完成了,效果如下


2.显示图片
我的做法是在数据库中存储相应图片的位置,然后将其显示
但是直观想法便是直接利用路径调用图片,但在django中不可行,因为django关于路径的管理会跳转到url.py中去寻找解决方案
import django.views.static
url(r‘^media/pictures/(?P<path>.*)‘, django.views.static.serve, {‘document_root‘: ‘d:/douban/Douban/media/pictures‘}),
这样每次遇到media/picture/的路径,他便会到‘document_root’后的值去找,而该值可由setting.py中的BASE_DIR与相对路径构成
改为
url(r‘^media/pictures/(?P<path>.*)‘, django.views.static.serve, {‘document_root‘: DouBan.settings.BASE_DIR+‘/media/pictures‘}),
完成,效果如图
