v1k45 / django-notify-x

Notification system for Django
MIT License
187 stars 40 forks source link

How to display a badge with the count of unread notifications? #31

Closed DanielFerreiraJorge closed 8 years ago

DanielFerreiraJorge commented 8 years ago

Hi, this is a great project! I just can't figure out how to display a badge showing the number of notifications! Thanks!

v1k45 commented 8 years ago

Hey @DanielFerreiraJorge , You can use django ORM's .count() method to count the number of notifications you want.

# to count all notifications
{{ user.notifications.count }}

# to count only unread notifications
{{ user.notifications.unread.count }}

# same with in the view
notification_count = request.user.notifications.count()
unread_notification_count = request.user.notifications.unread().count()
DanielFerreiraJorge commented 8 years ago

Hi, thank you very much for the answer!

It worked but I noticed that the number does not increase when new notifications are polled... is it possible to achieve this?

Thanks!

v1k45 commented 8 years ago

Yep, it is totally possible. That's what the AJAX update feature does for you.

The notification_update view fetches new notifications every 5 seconds, the JSON data returned has a both total retrieved and unread notification count.

You can override the update_success.js file (it is a simple js function based on jQuery) to modify the comment count badge every time new notifications are received as JSON data.

Something like:

var $nf_count_badge = $('.your-nf-count-badge')
$nf_count_badge.html(response.retrieved)
DanielFerreiraJorge commented 8 years ago

Haha... thanks!! very easy!

v1k45 commented 8 years ago

I am closing the issue assuming that I've answered all your concerns. Feel free to open the discussion if you didn't get your answer :+1:

kaiofreitas commented 5 years ago

Hi! I tried your solution but now, every time I reload the page the counter goes to 0.

Any suggestions on this?