Home / Blogs

How to Build a Real-Time Notification System With Django-notifications-hq

Django
·

August 16, 2023

how-to-build-a-real-time-notification-system-with-django-notifications-hq

In today’s fast-paced world, real-time notifications play a crucial role in keeping users engaged and informed. Whether it’s notifying users about new messages, friend requests, or updates on their favorite content, a real-time notification system enhances the user experience.

In this blog post, we will explore how to build a real-time notification system using the powerful Django package called Django-notifications-hq.

What is Django-notifications-hq?

Django-notifications-hq is a reusable Django app that provides a flexible and easy-to-use framework for handling notifications within your Django web application. It allows you to create, manage, and display real-time notifications to your users. It provides an intuitive API and integrates well with Django’s authentication system, making it an excellent choice for adding notification functionality to your project.

Setting Up the Environment:

To get started, make sure you have Django and Django-notifications-hq installed in your Python environment. You can install Django-notifications-hq using pip:

$ pip install django-notifications-hq

Once installed, add ‘notifications’ to the `INSTALLED_APPS` list in your Django project’s `settings.py` file:

INSTALLED_APPS = [
    ...
    'notifications',
    ...
]

Next, run the migrations to create the necessary database tables:

$ python manage.py migrate notifications

Creating Notification Types:

Before we dive into implementing the real-time notification system, let’s define the types of notifications your application needs. For example, you might have notification types like “New Message,” “Friend Request,” or “Post Liked.” Create a new model to represent the notification type:

from django.db import models

class NotificationType(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

Remember to run migrations to create the `NotificationType` table:

$ python manage.py makemigrations
$ python manage.py migrate

Creating the Notification Model:

Now, let’s create the `Notification` model to represent individual notifications:

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from notifications.models import Notification as BaseNotification

class Notification(BaseNotification):
    recipient = models.ForeignKey(User, on_delete=models.CASCADE)
    notification_type = models.ForeignKey(NotificationType, on_delete=models.CASCADE)
    # Additional fields specific to your notification

    class Meta:
        ordering = ['-timestamp']

Configuring Real-Time Notifications:

To enable real-time notifications, we need to configure the channels layer for Django Channels. First, install Django Channels

$ pip install channels

Next, add ‘channels’ to the `INSTALLED_APPS` list in your Django project’s `settings.py` file:

INSTALLED_APPS = [
    ...
    'channels',
    ...
]

Create a new file called `routing.py` in your project’s root directory and add the following code:

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from notifications.routing import websocket_urlpatterns

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(websocket_urlpatterns),
})

Lastly, update your project’s `asgi.py` file to use the new routing configuration:

import os
from django.core.asgi import get_asgi_application
from .routing import application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")

django_asgi_app = get_asgi_application()

application = application

Displaying Notifications:

To display notifications to users, create a view that fetches the notifications for the authenticated user:

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from notifications.models import Notification

@login_required
def notifications_view(request):
    notifications = Notification.objects.filter(recipient=request.user)
    return render(request, 'notifications.html', {'notifications': notifications})

In the `notifications.html` template, you can iterate over the notifications and display them to the user:

To read more about enhance user notifications with Django messages framework, refer to our blog How to Enhance User Notifications With Django Messages Framework

Conclusion:

In this blog post, we explored how to build a real-time notification system using Django-notifications-hq. By leveraging this powerful Django package, you can easily implement real-time notifications in your web application. From setting up the environment to configuring real-time notifications with Django Channels, you have learned the essential steps to implement a robust notification system. Now, it’s time to enhance your application’s user experience by keeping your users informed and engaged with real-time notifications!

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.