如何在Django中通过Admin上传并在HTML显示可修改头像?
解决Django头像上传与页面显示问题
1. 修正模型定义问题
你的ProfileImage模型中ImageField的upload_to参数设为None,Django无法确定图片存储路径,需指定具体目录,同时补充媒体文件配置:
- 模型修改:
class ProfileImage(models.Model): profile = models.ImageField("Profile image", upload_to='profile_pics/', height_field=None, width_field=None, max_length=None) def __str__(self): return "Profile Image"
- 在项目
settings.py中添加媒体文件配置:
MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/'
- 在项目根
urls.py中添加媒体文件路由:
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # 你的其他路由配置 ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
2. 视图传递头像实例到模板
不能直接在模板中调用模型类属性,需通过视图将ProfileImage的实例传递给模板:
from django.shortcuts import render from .models import ProfileImage def home(request): # 取已上传的第一个头像实例,可根据需求调整筛选逻辑 profile_image = ProfileImage.objects.first() return render(request, 'base.html', {'profile_image': profile_image})
3. 修正模板代码
模板存在拼写错误(progile应为profile),且需使用视图传递的实例对象:
{% if profile_image %} <img src="{{ profile_image.profile.url }}" alt="profile"><br /> {% else %} <p>暂无上传头像</p> {% endif %}
添加if判断可避免未上传头像时模板报错。
4. 测试验证
- 执行
python manage.py makemigrations和python manage.py migrate更新数据库 - 启动服务后进入Admin后台上传头像
- 访问对应视图页面即可看到头像
内容的提问来源于stack exchange,提问作者l3ekzod Khalikulov
相关产品推荐
相关产品推荐

