Search code examples
pythondjangodjango-signals

How to automatically update view once the database is updated in django?


I have a problem in which I have to show data entered into a database without having to press any button or doing anything. I am creating an app for a hospital, it has two views, one for a doctor and one for a patient. I want as soon as the patient enters his symptoms, it shows up on doctor immediately without having to press any button. I have no idea how to do this. Any help would be appreciated. Thanks in advance


Solution

  • The way a standard web framework like Django works is that it expects a request input and provides an output.

    Request -> (Nginx/Gunicorn/...) -> Django -> Output -> (Html/JSON/XML)
    

    The request is what happens when you type an address in your browser and press enter, or when you send an Ajax request (same thing, but without pressing enter and refreshing the page).

    There is no way for Django alone to do something like this:

    (An event on your server) -> Django -> your browser
    

    Django doesn't know where your browser is. Your browser knows where he is, but not the other way around.

    In the past, we used to solve this problem by setting a timer in JavaScript that refreshes the page every n seconds.

    setTimeout(function(){
       window.location.reload(1);
    }, 5000);
    

    Nowadays, the better solution is to use websockets. Client-side, they look like this:

    let mySocket = new WebSocket("ws://www.example.com/socketserver");
    
    mySocket.onmessage = function (event) {
      console.log(event.data);
    }
    

    This assumes that in "ws://www.example.com/socketserver" you are serving a web socket, a server that sends out messages to all clients listening whenever you tell it to.

    Django cannot do this for you: it expects the first kind of interaction and only that.

    The server side software that is usually recommended for web sockets, if you already have your program in Django or if you're well versed only in it, is Celery.

    Read about it here: https://celery.readthedocs.io/en/latest/getting-started/introduction.html

    This might represent quite a bit of complexity for your application.

    Another alternative is NodeJS, a runtime environment that is 100% async.