In this tutotrial, we are going to setup the Notification alert in our web application using Django and Javascript
Step 1:
Lets create the project in Django using below command
django-admin startproject notification
Step 2:
Now, we can create the app and add the new in settings.py
python manage.py startapp notify
Step 3:
We need to create the models to hold the Sender, Receiver, Model Object info into our new model. So we can create the models using ContentType(which is out of the box from Django)
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
class Notification(models.Model):
recipient = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=False,
on_delete=models.CASCADE
)
target_content_type = models.ForeignKey(
ContentType,
blank=True,
null=True,
on_delete=models.CASCADE
)
sender = models.ForeignKey(ContentType,
on_delete=models.CASCADE)##(It should be our User model)
unread = models.BooleanField(default=True, blank=False, db_index=True)
So now we have model have to hold our data. Now ,its time to think about how can we send the trigger when sender sends some content to Receipeint. At the moment when we say trigger then obviously we have to go with SIGNALS.
Step 4:
Lets create the signals.py to handle the trigger,
##signals.py
from django.dispatch import Signal
notify = Signal(providing_args=[
'recipient', 'sender', 'target'
])
Step 5:
Now, we can create the connect & receiver to handle the signals.
## in models.py
from .signals import notify
def notification_receiver(sender, instance, request, *args, **kwargs):
user = None
if request.user.is_authenticated:
user = request.user
new_view_obj = ObjectViewed.objects.create(
sender= user,
receiver = instance.user
target=instance.target,
unread=instance.unread,
)
notify.connect(notification_receiver)
Step 6:
Using this signal we can implement the mixin or we can use signal directly in our views. Lets say you have Video detail page, where user wants to comments it, then below is the way to trigger the signal,
request.User => Sender(models)
Target_model_instance => Target(Content Type)
Recipient => Target Object owner
Step 7:
Example, we can include the below signal in our view function when user comments on a given page,
notify.send(sender=request.user,
recipient=instance.user,
target=instance)
Now, its time to handle the Javascript to handle the notification automatically, may be we can try for every 5 secs AJAX request to the backend,
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, Teckiys!</h1>
<div id="load-notification></div>
</body>
</html>
Its simple html code with div id="load-notification". This is where , we are going to load the notification count automatically every 5 secs,
Step 8:
const loadNotifyElement = document.getElementById("load-notification");
function loadNotification() {
fetch("{URL}", {
method: "GET",
.then(response => {
if (response.status !== 200) {
throw new Error(response.status)
}
else {
return response.json()
}
})
.then(data => {
let finalNotifyCount = "";
var currentItem = `${data.length}`
finalNotifyCount += currentItem;
loadNotifyElement.innerHTML = finalNotifyCount;
})
}
setInterval(loadNotification, 5000);
We just need to include the above JS to handle the Asynchrous request to backend top get the notifications.
In case of any queries, please raise the support ticket here ,Support (Techions will help you on it).
Happy Coding !!!