Django表单无法获取上传头像,始终显示默认头像求助
问题:Django表单提交时头像无法保存,始终显示默认头像
提交表单时,bio、location等数据可正常保存,但上传的头像无法被获取,始终显示默认头像defaultdp.png。以下是相关代码:
Profile模型代码
class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='defaultdp.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username
HTML表单代码
<form action="" method="POST" enctype="multipart/form-data"> {%csrf_token%} <div class="col-span-2"> <label for=""> Profile Picture</label> <img height="100" width="100" src="{{user_profile.profileimg.url}}"> <input type="file" name="profileimg" placeholder="" class="shadow-none bg-gray-100"> </div> <form>
视图函数代码
@login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == 'POST': if request.FILES.get('image') == None: image = user_profile.profileimg bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() if request.FILES.get('image') != None: image = request.FILES.get('image') bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() return redirect('settings') return render(request,'setting.html',{'user_profile': user_profile})
问题排查与修复
核心字段名不匹配:表单中文件输入框的
name属性是profileimg,但视图代码里一直尝试从request.FILES.get('image')获取文件,字段名不一致导致永远取不到上传的头像文件,只能使用默认值。修复步骤:
- 将视图中所有
request.FILES.get('image')替换为request.FILES.get('profileimg') - 优化冗余的判断逻辑,合并为更简洁的写法
- 将视图中所有
修改后的视图代码:
@login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user=request.user) if request.method == 'POST': # 获取上传的头像,没有则保留原头像 image = request.FILES.get('profileimg') or user_profile.profileimg bio = request.POST['bio'] location = request.POST['location'] user_profile.profileimg = image user_profile.bio = bio user_profile.location = location user_profile.save() return redirect('settings') return render(request,'setting.html',{'user_profile': user_profile})
- 额外检查项:
- 确保项目配置中已正确设置
MEDIA_ROOT和MEDIA_URL,否则即使头像保存成功,前端也无法正确显示:# settings.py MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' - 在项目的根URL配置中添加媒体文件的路由:
# urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # 其他路由 ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 确保项目配置中已正确设置
内容的提问来源于stack exchange,提问作者noobintech
相关产品推荐
相关产品推荐

