Django通知系统HTML模板无法渲染通知内容问题求助
问题原因及解决方案
核心错误:上下文变量名不匹配
你在views.py中传递给模板的上下文变量名为notify,但HTML模板中遍历的变量名是notifications,两者不一致导致模板无法拿到通知数据,自然不会渲染任何内容。
其他可排查的小问题
- 模板中判断通知类型的字符串
"New Comment",需要和数据库中实际存储的notification_type值完全一致,包括大小写、空格 - 模板中拼写错误
commnet应为comment,不影响渲染但会导致显示内容错误
修复方法
二选一即可,保证上下文变量名和模板调用名统一:
- 修改模板代码:将
{% for notification in notifications %}替换为{% for notification in notify %} - 或者修改
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
相关产品推荐
相关产品推荐

