Reputation: 85
X
and Y
are two Person
s. X
sends a friend request to Y
so in Y
s profile there will be a notification of friend request. Then Y
accept the Friend request so in X
profile also be appeared a notification of accepting friend request.
I know real time notification can be handle by Django channel and it will be solve by creating group by user.
But is it best practice to create group for every particular user? Is there another way to solve this problem?
Upvotes: 3
Views: 2760
Reputation: 6107
The easiest way to send a message to an individual user is to add that user to their own group on your consumer's connect()
method.
class Consumer(WebsocketConsumer):
def connect(self):
self.group_name = self.scope['user'].pk
# Join group
async_to_sync(self.channel_layer.group_add)(
self.group_name,
self.channel_name
)
self.accept()
Every time a user visits a page specified in yourapp.routing.websocket_urlpatterns
they'll be automatically added to the group so there isn't much work to do.
Sending the message is also easy because you already have both target user.pk
s required for the messages.
def ajax_accept_friend_request(request):
friend = request.GET.get('id', None)
channel_layer = get_channel_layer()
# Trigger message sent to group
async_to_sync(channel_layer.group_send)(
friend,
{
'type': 'your_message_method',
'accept': True
}
)
return HttpResponse()
Upvotes: 1