3

X and Y are two Persons. X sends a friend request to Y so in Ys 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?

1 Answer 1

1

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.pks 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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.