I have been trying to implement user specific real time notifications in a project. While I was able to broadcast the real time notifications, I am facing a stiff struggle to create user specific channels, where selected notifications are sent to user. As far as my attempt for the same goes, following are the pieces of code that I have written after looking at a few examples using swampdragon-auth:
routers.py:
class NotificationRouter(ModelPubRouter):
valid_verbs = ['subscribe']
route_name = 'notifications'
model = Notification
serializer_class = NotificationSerializer
def get_query_set(self, **kwargs):
return self.model.objects.filter(user=self.connection.user)
def get_object(self, **kwargs):
return self.model.objects.get(user=self.connection.user, pk=kwargs['pk'])
def get_subscription_contexts(self, **kwargs):
return {'user__id': self.connection.user.pk}
models.py
class Notification(SelfPublishModel, models.Model):
serializer_class = NotificationSerializer
message = models.TextField()
verb = models.CharField(null=True, default="achieved", max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
and serializer.py
class NotificationSerializer(ModelSerializer):
class Meta:
model = 'notifications.Notification'
publish_fields = ['message','verb','user']
This code does not achieves the user specific notifications execution and broadcasts messages to all users. As far I believe, get_subscription_contexts is the function which filters the notifications to selected users, but I am not able to achieve that with this code. It would be great if anyone could help me resolve this issue.
Thanks
Himanshu
Testing your code out in a sample project, and adding two users, I am receiving notifications only for my logged in user as expected.
Can you confirm the version of SwampDragon you are using?
Tested with:
I've created a demo project with the above implemented - https://github.com/CptLemming/swampdragon_notification_example
In this example I can login to the Django admin, create a notification, and have notifications only appear for the selected user.
Hope it helps.