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

Django中用户上传头像无法保存及显示问题求助

问题排查与修复

核心错误:表单缺少文件上传必需的编码属性

你的表单未设置enctype="multipart/form-data",这是Django中上传文件的必填配置——没有该属性时,浏览器无法正确传递文件数据,导致request.FILES为空,头像自然无法保存。

修复后的setting.html表单代码

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="grid grid-cols-2 gap-3 lg:p-6 p-4">
<div class="col-span-2">
   <label for="">Profile Image</label>
   <img width = "100" height = "100" src="{{user_profile.profileimg.url}}"/>
   <input type="file" name='image' value = "" placeholder="No file chosen" class="shadow-none bg-gray-100">
</div>
<div class="col-span-2">
   <label for="about">Bio</label>  
   <textarea id="about" name="bio" rows="3"  class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea>
</div> 
<div class="col-span-2">
   <label for=""> Location</label>
   <input type="text" name = "location" value = "{{user_profile.location}}" placeholder="" class="shadow-none bg-gray-100">
</div>
 </div> 
                                
 <div class="bg-gray-10 p-6 pt-0 flex justify-end space-x-3">
 <button class="p-2 px-4 rounded bg-gray-50 text-red-500"> <a href="/"> Cancel</a> </button>
 <button type="submit" class="button bg-blue-700"> Save </button>
 </div>
 </form>

可选优化点

  1. 简化views.py逻辑:避免重复代码,统一处理字段赋值:
@login_required(login_url='signin')
def settings(request):
    user_profile = Profile.objects.get(user=request.user)
    if request.method == "POST":
        # 优先使用上传的文件,无文件则保留原头像
        user_profile.profileimg = request.FILES.get('image', user_profile.profileimg)
        user_profile.bio = request.POST['bio']
        user_profile.location = request.POST['location']
        user_profile.save()
        return redirect("settings")

    return render(request, 'setting.html', {'user_profile': user_profile})
  1. 模型字段精简:id_user字段可删除,因为user外键已关联用户,通过user.id即可获取用户ID,无需额外存储冗余数据。

验证步骤

  1. 确认项目根目录下media文件夹存在且具备读写权限
  2. 重启Django服务,重新上传头像测试

内容的提问来源于stack exchange,提问作者Vijay Krishna Narsingoju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:00:52