Django,显示基本模板中未读消息的计数

时间:2013-06-28 15:34:41

标签: django django-templates facebook-messages

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

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

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

1 个答案:

答案 0 :(得分:3)

你可以写一个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 %}
相关问题