3 Mins Read  August 20, 2015  Cuelogic

Adding real-time notification to Django

Adding-real­time-notification-to-Django

High level of user engagement and notification are vital for the long term success of an app so it is important you do everything to encourage engagement and interaction amongst users when it comes to creating app with user to user interaction it is important to keep users on your app and make sure they are engaged

Online notification systems allow users to be alerted to actions that directly affect them in real-time. Without an online notification system users will find it much more difficult to keep track of their interactions.

This shows how to implement a simple realtime notification system in a Django app

Generating Notifications:

Generating notifications is probably best done using signals.

from django.db.models.signals import post_save from notifications import notify from myapp.models import MyModel def my_handler(sender, instance, created, **kwargs): notify.send(instance, verb=’was saved’) post_save.connect(my_handler, sender=MyModel)

to generate an notification anywhere in your code, simply import the notify signal and send it with your actor, recipient, verb, and target. 

from notifications import notify notify.send(user, recipient=user, verb=’you reached level 10′) notify.send(comment.user, recipient=user, verb=u’replied’, action_object=comment, description=comment.comment, target=comment.content_object) notify.send(follow_instance.user, recipient=follow_instance.follow_object, verb=u’has followed you’, action_object=instance, description=u”, target=follow_instance.follow_object, level=’success’)

Extra data:

You can attach arbitrary data to your notifications by doing the following:

Add to your settings.py: NOTIFICATIONS_USE_JSONFIELD=True

Then, any extra arguments you pass to notify.send(…) will be attached to the .data attribute of the notification object. These will be serialized using the JSONField’s serialiser, so you may need to take that into account: using only objects that will be serialized is a good idea. 

Soft delete:

By default, delete/(?P<slug>d+)/ deletes specified notification record from DB. You can change this behavior to “mark Notification.deleted field as True” by:

Add to your settings.py:NOTIFICATIONS_SOFT_DELETE=True

With this option, QuerySet methods unread and read contain one more filter: deleted=False. Meanwhile, QuerySet methods deleted, active, mark_all_as_deleted, mark_all_as_active are turned on. See more details in QuerySet methods section.

QuerySet methods:

Using django-model-utils, we get the ability to add queryset methods to not only the manager, but to all querysets that will be used, including related objects. This enables us to do things like:

Notification.objects.unread()

It returns all unread notifications. To do this for a single user, we can do:

user = User.objects.get(pk=pk) user.notifications.unread()

There are some other QuerySet methods, too.

qs.unread()

Return all of the unread notifications, filtering the current queryset. When
NOTIFICATIONS_SOFT_DELETE=True, this filter contains deleted=False.

qs.read()

Return all of the read notifications, filtering the current queryset. When
NOTIFICATIONS_SOFT_DELETE=True, this filter contains deleted=False.

qs.mark_all_as_read() | qs.mark_all_as_read(recipient)

Mark all of the unread notifications in the queryset as read.

qs.mark_all_as_unread() | qs.mark_all_as_unread(recipient)

Mark all of the read notifications in the queryset as unread.

qs.deleted()

Return all notifications that have deleted=True, filtering the current queryset. Must be used with NOTIFICATIONS_SOFT_DELETE=True.

qs.active()

Return all notifications that have deleted=False, filtering the current queryset. Must be used with NOTIFICATIONS_SOFT_DELETE=True.

qs.mark_all_as_deleted() | qs.mark_all_as_deleted(recipient)

Mark all notifications in the queryset as deleted=True. Must be used with NOTIFICATIONS_SOFT_DELETE=True.

qs.mark_all_as_active() | qs.mark_all_as_active(recipient)

Mark all notifications in the queryset as deleted=False. Must be used with NOTIFICATIONS_SOFT_DELETE=True.

Model methods:

obj.timesince([datetime])

It is a wrapper for Django’s timesince function.

obj.mark_as_read()

Mark the current object as read.

Template tags:

Put {% load notifications_tags %} in the template before you actually use notification tags.

notifications_unread

{% notifications_unread %}

Give the number of unread notifications for a user, or nothing (an empty string) for an anonymous user. Storing the count in a variable for further processing is advised, such as:

{% notifications_unread as unread_count %} … {% if unread_count %} You have <strong>{{ unread_count }}</strong> unread notifications. {% endif %}

Live-updater API:

To ensure users always have the most up-to-date notfications, django-notifications includes a simple javascript API for updating specific fields within a django template.

There are two possible API calls that can be made:

  • api/unread_count/ that returns a javascript object with 1 key: unread_count eg:

{“unread_count”:1}

  • api/unread_list/ that returns a javascript object with 2 keys: unread_count and unread_list eg:

{ “unread_count”:1, “unread_list”:[–list of json representations of notifications–] }

Representations of notifications are based on the django method: model_to_dict

Customizing the display of notifications using JavaScript callbacks:

While the live notifier for unread counts should suit most use cases, users may wish to alter how unread notifications are shown.

The callbacks argument of the register_notify_callbacks dictates which javascript functions are called when the unread API call is made.

To add a custom JavaScript callback, simply add this to the list, like so:

{% register_notify_callbacks callbacks=’fill_notification_badge,my_special_notification_callback’ %}

The above would cause the callback to update the unread count badge, and would call the custom function my_special_notification_callback. All callback functions are passed a single argument by convention called data, which contains the entire result from the API.

For example,

The below function would get the recent list of unread messages and log them to the console:

function my_special_notification_callback(data) { for (var i=0; i < data.unread_list.length; i++) { msg = data.unread_list[i]; console.log(msg); } }

Recommended Content

Go Back to Main Page