Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by twrought for Trigger javascript function from Django server

This is 100% possible with Django using Websockets. It sounds like you are trying to build a notification system for the UI based on when you receive a request at one of your urls. Start by checking out Django Channels: https://channels.readthedocs.io/en/stable/

This is the best way to use Websockets with Django, which can help you implement notifications or other real-time features. The tutorial in the docs is great. To solve your task, you should:

  • Follow the tutorial and set up a WebSocket consumer in your Django app to handle notifications. This is what will allow a frontend user to establish a real-time connection with your application and receive messages from it.
  • Finish your notifications_view. After the request from the payment comes in, you will be dispatching a message to your websocket consumer for whichever user needs to recieve the message. It could end up looking something like this:
# assuming that the request gives you the username of the user to be notified,# and you have a group configured in your consumerdef notification_view(request):     if request.method == "POST":          username = request.POST.get('username')          group_name = 'notifications{}'.format(username)          channel_layer = channels.layers.get_channel_layer()          async_to_sync(channel_layer.group_send)(                 group_name,                 {'type': 'new_payment','text': {'eventType': 'notification','name': 'New Payment','userMessage': 'You just got paid'                     }                 }     return(HttpResponse(status=200))

This would send a message over the user's socket when the request is received.

In your js, you will setup a listener for the socket. Then you can listen for the messages and do whatever you desire in the document with the data you recieve, such as show a user a message:

var endpoint = 'ws://'+'<yourhost>/notifications/username/;var socket = new ReconnectingWebSocket(endpoint);socket.onmessage = e => {     data = JSON.parse(e.data);     let msg = document.createElement('<p>');     msg.innerText = data['text']['userMessage']     }

Just follow the tutorial and that will certainly get you headed in the right direction!


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles