【问题标题】:Django, display count of unread messages in base templateDjango,在基本模板中显示未读消息的计数
【发布时间】:2013-06-28 15:34:40
【问题描述】:

我正在开展一个项目,在该项目中我实现了像 facebook 这样的消息传递系统,用户可以在其中相互发送消息。特定线程的未读消息数也会显示在消息页面上。

现在我想要的是每次用户登录时在导航栏中显示未读消息的计数(在base.html中)。用户登录时如何执行此操作?

请提出建议,我不想为此目的使用任何其他应用程序。谢谢

【问题讨论】:

  • 你在使用用户档案模型吗?
  • @karthikr:实际上没有
  • 我过去做过类似的事情,我通过 ajax 调用视图。您甚至可以让 js 部分每 n 秒执行一次,以便在收到新消息时更新
  • @la_f0ka: 好吧,我想我也需要这样做,以便在一段时间后继续更新页面,谢谢

标签: django django-templates facebook-messages


【解决方案1】:

你可以写一个simple tag,它可以为你做这件事。

def unread_messages(user):
    return user.messages_set.filter(read=False).count()
    #replace the messages_set with the appropriate related_name, and also the filter field. (I am assuming it to be "read")

register.simple_tag(unread_messages)

在基础模板中:

{% load <yourtemplatetagname> %}

{% if request.user.is_authenticated %}
    {{ request.user|unread_messages }}
{% endif %}

【讨论】:

  • 它向我显示以下错误:TemplateSyntaxError 无效过滤器:'unread_messages'
  • 你可能忘记{% load %}模板标签
  • 是的,我错过了这个,这种方法会帮助我,谢谢伙计
猜你喜欢
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2014-01-29
相关资源
最近更新 更多