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:

models.py

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('user'), related_name='notifications')
    content_type = models.ForeignKey(
        ContentType,
        models.SET_NULL,
        verbose_name=_('content type'),
        blank=True,
        null=True
    )
    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:

context_processors.py

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

Then this is executed on every request:

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'colossus/templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # notifications context processor:
                'colossus.apps.notifications.context_processors.notifications',
            ],
        },
    },
]

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