Search code examples
mongodbdjango-viewspush-notification

Django: How to send a notification to the front-end when a MongoDB document is updated


I am developing a Django App using MongoDB Atlas as database. I would like Django to receive a notification to the front-end when a document is inserted or modified. For example, an external client sends data to MongoDB by filling a form in a browser. Then, Django detects the new data and notify the front-end with a message. I have learned about the MongoDB built-in function my_collection.watch(). However, I am struggling on how to implement it in a view.py so the output of my_collection.watch() can be sent to the front-end with return render( request, 'webpage.html' ).

Sorry if it is a silly issue, but I am still learning. Any suggestion?

Thank you very much in advance for your help!


Solution

  • I have two responses to this:
    A) If you're doing your first steps in django, drop the topic and move to something easier.
    B) If you are familiar with django and its deployment use websockets to implement it.

    Explanation for A):
    You get the fact right, that there is a distinct separation between frontend and backend. Anyhow django kind of contains both. Views and models are the backend, templates and static files the frontend.

    The backend, meaning the views, will always have the chance to provide logic when the user clicks a link, meaning sends a request. For the scenario that your user is viewing the products page and another product gets added to the product database, there is no refresh of the site, as the user is not clicking any links, not sending a new request. That's why the views/backend logic can not send the new data, including the new product to the user. Long story short: The user sends the request, django assembles the response and sends it back, connection closed. There is no scenario where django sends data to the user without the user having sent a request.

    Explanation for B):
    You can achieve what you want in two ways. Option 1: Websockets, Option 2: constantly requesting of new data.

    Option 1) Websockets allow you to overcome the issue I explained above. They keep the channel between the user and the backend open allowing django to keep sending data. This requires asynchronous deployment via asgi whereas 'normal' django, synchronous django, is deployed via uwsgi. In addition you need your frontend to accommodate for that continuous connection, to keep listening to the connection.

    Option 2) Instead of a full view with a template you could add a view just serving a JSONResponse returning all data for the products. Via javascript in your template you then keep fetching - maybe every 3 seconds - the data for the products from this endpoint. You dynamically merge the data from the jsonresponse then into your template.