djangodjango-templatesfacebook-messages

Django, display count of unread messages in base template


I am working on a project in which I have implemented messaging system like facebook where users can send messages to each other. The number of unread messages of a particular thread is also displayed on the messages page.

Now what I want is to display the count of unread messages in the navigation bar (which is there in base.html) each time user logs in. How to do this whenever a user logs in?

Please suggest, and I don't want to use any other app for this purpose. Thanks


Solution

  • You can write a simple tag which can do this for you.

    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)
    

    and in the base template:

    {% load <yourtemplatetagname> %}
    
    {% if request.user.is_authenticated %}
        {{ request.user|unread_messages }}
    {% endif %}