Django中如何在BlogView页面获取关联Profile模型的profile_pic字段值
Django 博客列表页作者头像获取方案
首先明确模型关联逻辑:Profile 和 User 是一对一关联,没有指定反向关联名的情况下,Django默认会生成profile作为反向访问名,可直接从User实例访问关联的Profile数据。
1 核心src属性写法
你当前使用的ListView返回的上下文是StudentBlogModel_list博客对象列表,需要先遍历该列表才能逐个获取单条博客的作者信息,img标签的src核心取值为单条博客实例.author.profile.profile_pic.url,同时建议加空值判断避免用户未上传头像时触发报错。
完整修改后的模板参考:
<div class="container"> <div class="row"> <div class="col-lg-8"> <hr> <div class="profile-feed"> <!-- 新增列表遍历逻辑,原模板直接调用StudentBlogModel是错误的 --> {% for blog in StudentBlogModel_list %} <div class="d-flex align-items-start profile-feed-item"> <!-- 头像标签,空值时展示默认占位图,可自行替换默认图路径 --> <img src="{% if blog.author.profile.profile_pic %}{{ blog.author.profile.profile_pic.url }}{% else %}/static/images/default_avatar.png{% endif %}" alt="profile" class="img-sm rounded-circle mb-5 mx-2"> <div class="ml-4"> <h6> {% if blog.author.first_name or blog.author.last_name%} <small class="card-title">{{blog.author.first_name|capfirst}} {{blog.author.last_name|capfirst}} </small> {% else %} <small class="card-title">{{blog.author.username|capfirst}}</small> {% endif %} <small class="ml-4 text-muted"><i class="mdi mdi-clock mr-1"></i> {{blog.post_date}}</small> </h6> <p> {{blog.title}} </p> <!-- 剩余原有博客内容代码保持不变 --> </div> </div> {% endfor %} <!-- 遍历结束 -->
2 开发环境图片访问补充配置
要避免图片返回404,需要确认项目已配置MEDIA资源访问规则:
- settings.py中添加配置:
MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / '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)
内容的提问来源于stack exchange,提问作者James_56
相关产品推荐
相关产品推荐

