如何将Django中Coach模型数据渲染至lesson_detail.html页面?
问题解决步骤
核心问题分析
- 模型关联缺失:
Lesson与Coach模型之间未建立关联关系,无法通过当前课程匹配到对应教练。 - 变量未定义错误:代码中
get_object_or_404(Coach, first_name=first_name)里的first_name变量未定义,直接引发报错。
解决方案
步骤1:建立Lesson与Coach的关联
在models.py的Lesson模型中添加外键字段,关联到Coach(假设一个课程对应一位教练):
# models.py class Lesson(models.Model): # 保留你已有的其他字段(如status、slug等) coach = models.ForeignKey(Coach, on_delete=models.CASCADE, related_name='lessons')
添加后执行数据库迁移:
python manage.py makemigrations python manage.py migrate
步骤2:修正视图中的Coach获取逻辑
在LessonDetail视图的get方法中,通过已获取的lesson对象直接关联到对应教练,替换原有错误的get_object_or_404调用:
# views.py def get(self, request, slug, *args, **kwargs): queryset = Lesson.objects.filter(status=1) lesson = get_object_or_404(queryset, slug=slug) # 通过课程关联直接获取对应教练 coach = lesson.coach feedbacks = lesson.feedbacks.filter(approved=True).order_by('-created_on') # 其余代码保持不变...
步骤3:验证模板显示
此时模板中的{{ coach.first_name }}、{{ coach.last_name }}等变量可正常显示教练数据,视图已将正确的coach对象传入模板上下文。
内容的提问来源于stack exchange,提问作者yamesjames
相关产品推荐
相关产品推荐

