因为自己在这一块走了点弯路,现在在这里做一个记录为日后作为参考。
网上对于Django的动态上传图片的完整实例不多,对于初学者来说是一个比较痛苦的事情。都要慢慢的去推敲。不说这么多了看具体。
上传图片:
我这边用的是sqlite3数据库
用到的代码:
models.py
from __future__ import unicode_literals
from django.db import models
class Articles(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
#这一块是图片上传过来后储存到数据库中
headImg = models.ImageField(upload_to='')
在settings.py中设置储存路径
MEDIA_ROOT = 'blog/static/'
views.py
这一块就是具体的图片上传代码
if request.method == "POST":
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
content = uf.cleaned_data['content']
title = uf.cleaned_data['title']
img = uf.cleaned_data['headImg']
new = Articles(content=content, title=title, headImg=img)
new.save()
return HttpResponseRedirect('/blog/list')
else:
uf = UserForm()
return render_to_response('add.html',{'form':uf})
在这上传图片的代码中我犯了一个比较大的错误,就是在models中的headImg = models.ImageField(upload_to='')写了上传的路径,这样写是能上传图片没有为题,但问题在于这样写了在html中获取的图片name就是路径加图片名称,这样就让我们的html代码获取不到图片地址加载不了图片了。上面的代码才是正确的写法切记。
获取图片代码:
views.py
articles = Articles.objects.order_by("-id").all()
return render_to_response('list.html',{'articles':articles})
settings.py
STATIC_URL = '/blog/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'blog')
html
<img class="st_camera" src={% static article.headImg %} width="500" height="500">
这里就是图片的上传和将图片展示到了web页上。
网友评论