Django real-time notifications with SwampDragon

Published: 09 Dec 2014

A lot of websites display notifications in one form or another these days. Facebook shows the new message notification, Gmail have the new mail notifications (with the support of browser notifications).

I was asked today how hard it would be to implement a real-time notification system. The answer, as it turns out, is: not very hard at all.

Setup

First step is to install SwampDragon.

pip install swampdragon

Models

We store the notification as a model. This way we can load existing notification when the user loads the page the first time.

from django.db import models
from swampdragon.models import SelfPublishModel
from .serializers import NotificationSerializer

class Notification(SelfPublishModel, models.Model):
    serializer_class = NotificationSerializer
    message = models.TextField()

Serializers

Add a new file: demo/serializers.py to specify the publish fields:

from swampdragon.serializers.model_serializer import ModelSerializer

class NotificationSerializer(ModelSerializer):
    class Meta:
        model = 'demo.Notification'
        publish_fields = ['message']

Conclusion

With the router and view set up, you can now push notifications in real-time. By connecting your SwampDragon server (python server.py) alongside your Django runserver, the WebSocket connection handles the bi-directional communication required for instant updates.