You need to enable JavaScript to run this app. Django通知系统HTML模板无法渲染通知内容问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Django通知系统HTML模板无法渲染通知内容问题求助

问题原因及解决方案

核心错误:上下文变量名不匹配

你在views.py中传递给模板的上下文变量名为notify,但HTML模板中遍历的变量名是notifications,两者不一致导致模板无法拿到通知数据,自然不会渲染任何内容。

其他可排查的小问题

  • 模板中判断通知类型的字符串"New Comment",需要和数据库中实际存储的notification_type值完全一致,包括大小写、空格
  • 模板中拼写错误commnet应为comment,不影响渲染但会导致显示内容错误

修复方法

二选一即可,保证上下文变量名和模板调用名统一:

  1. 修改模板代码:将{% for notification in notifications %}替换为{% for notification in notify %}
  2. 或者修改views.py的上下文配置:将context字典里的键从notify改为notifications,即
context = {
    'notifications': notifications,
}

可选优化

可以在for循环中增加空数据提示,方便后续排查:

{% for notification in notify %} 
    {% if notification.notification_type == "New Comment" %}
        @{{ notification.sender.username }} You have received new comment 
        <p>{{ notification.text_preview }}</p>
    {% endif %}
{% empty %}
    <p>暂无通知</p>
{% endfor %}

内容的提问来源于stack exchange,提问作者boyenec

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:45:00