You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

django-notifications-hq中mark_as_read函数使用异常问题求助

解决django-notifications-hq点击通知标记已读并跳转的问题

你的问题根源很明确:直接在模板里写{{notification.mark_as_read}}时,模板渲染阶段就会执行这个方法——也就是说,只要打开通知下拉菜单,通知就被标记成已读了,完全不是你想要的「点击时触发」的时机。

给你一套可行的解决思路,用中间视图来处理标记逻辑:

  1. 新增处理标记+跳转的视图函数
from django.shortcuts import get_object_or_404, redirect
from notifications.models import Notification

def mark_notification_read_and_redirect(request, notification_id):
    # 确保只能操作当前用户的通知
    notification = get_object_or_404(Notification, id=notification_id, recipient=request.user)
    # 避免重复标记已读
    if notification.unread:
        notification.mark_as_read()
    # 跳转到关联的帖子详情,这里假设通知的action_object是帖子实例
    post = notification.action_object
    return redirect('post_detail', pk=post.pk)  # 替换成你自己的帖子详情视图名称
  1. 在urls.py中添加对应路由
from django.urls import path
from .views import mark_notification_read_and_redirect

urlpatterns = [
    # 其他现有路由...
    path('notification/<int:notification_id>/read-redirect/', mark_notification_read_and_redirect, name='mark_notification_read_redirect'),
]
  1. 修改模板中的通知链接
    把原来的跳转链接改成指向这个新视图:
<a href="{% url 'mark_notification_read_redirect' notification.id %}">{{ notification.verb }}</a>

这样操作后,只有用户点击通知链接时,才会触发标记已读的动作,完成后再跳转到帖子详情页面,完美解决你遇到的两个问题。

如果你的通知关联的不是帖子,而是其他模型,只需要调整视图里获取跳转目标的逻辑即可,核心就是用中间视图接管「标记已读」的触发时机,而不是在模板里直接调用方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:27:15