You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 14:54:06