Notification system in Django

(Shekhar Nunia) #1

Hey guys,
I’m thinking to make a notification system in my project so that users can get notified when anything occurs, like in facebook we get notifications, or in twitter or more close in our community forum at top right corner.
Can anyone tell what should be the approach to build it and show it to users. It will be helpful if you share some of your thoughts.
Thank you :blush:

(Immanuel) #2

Please check out this post on the blog. Pay attention to the first project mentioned (Bootcamp). @Vitor implemented a Notifications Center which I think will be of great help. Grab the code and dig in!

(Vitor Freitas) #3

Another example of notification system is on a project I’m currently developing:

You can check the notifications app. It’s not 100%, but the overall mechanism is working fine.

Just so you can have an overall idea, I have a model with a generic relation:

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('user'), related_name='notifications')
    content_type = models.ForeignKey(
        verbose_name=_('content type'),
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey()
    action = models.PositiveSmallIntegerField(_('action'), choices=Actions.CHOICES)
    text = models.TextField(_('text'), blank=True)
    date = models.DateTimeField(_('date'), auto_now_add=True)
    is_seen = models.BooleanField(_('seen status'), default=False)
    is_read = models.BooleanField(_('read status'), default=False)

So the notifications can be associated with any model in my app

And a key point is a context processor I have:

def notifications(request):
    if request.user.is_authenticated:
        count = request.user.notifications.filter(is_seen=False).count()
        return {
            'notifications_count': count
        return dict()

Then this is executed on every request:

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'colossus/templates')
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # notifications context processor:

This counter I use to display a badge with notifications. And the loading of the notification is done using ajax requests. You can check the notifications.js file