Django博客用户上传图片无法显示返回404错误如何解决
问题原因
一共有3处错误导致图片无法正常上传和展示:
- 表单未配置文件上传所需的编码属性,浏览器不会将选中的图片文件提交给后端
- 视图中错误地从POST参数中提取图片,Django上传的文件都存储在
request.FILES对象中,不在request.POST里 - 模板硬拼接图片路径,很容易因为路径规则修改出现404,应该用Django自带的URL属性生成
解决步骤
1. 修改editor.html表单的编码属性
找到form标签,添加enctype="multipart/form-data"属性,修改后代码:
<form method="POST" action="/blogs/createblog" enctype="multipart/form-data">{% csrf_token %}
2. 修改createblog视图中获取图片的逻辑
把pic=request.POST.get("pic")改为从request.FILES取值,修改后代码:
def createblog(request): if request.method=="POST": author=request.POST.get("author") title=request.POST.get("title") today=date.today() category=request.POST.get("category") heading=request.POST.get("heading") body=request.POST.get("body") about=request.POST.get("about") # 从FILES中取图片,不是POST pic=request.FILES.get("pic") new_post=BlogPost(author=author,title=title,pub_date=today,category=category,heading2=heading,content2=body,about=about,image=pic) new_post.save() messages.success(request,"Your blog is published successfully.") return redirect("/blogs") return render(request,"blog/editor.html")
3. 修改yourblogs.html中的图片路径写法
不要硬写/media/{{blog_item.image}},直接调用ImageField的url属性自动生成路径,修改后代码:
<img src="{{blog_item.image.url}}" class="bd-placeholder-img" width="250" height="250" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false">
内容的提问来源于stack exchange,提问作者Palash Vishnani
相关产品推荐
相关产品推荐

