Py_2019
Py_2019

Reputation: 27

Dynamic content colouring change base on events in Django

Is it possible to create two boxes simulated network devices and line connecting them simulating the actual network connection(attached picture) in my html template. And have them change colour from green to red upon certain events coming from views.py.

Dynamic Boxes and line

Let say I have the below simple code from views.py:

snmpvalues = 'output taken from pysnmp' ### Code not included ###
def netstat(request):
    for line in snmpvalues: 
        if line == '1':
            return ('Green') ### Network is up ###
        else:
            return ('red') ### System is down ###

Based on the above code. I want to change the colours of the two boxes and line from either green (Network is up) or red (Network is down).

Can this be done?

Your help is greatly appreciated as usual.

Upvotes: 1

Views: 234

Answers (1)

iliya
iliya

Reputation: 531

You should use JQuery/Ajax to manipulate DOM and fetch data. Following code can make it clear how to do the job :

(function chColor() {
    $.ajax({
            type: "GET",
            url: "url to your view",
            success: function (data) {
                // here you can get data from backend and do changes like
                // changing color by the data coming from your view.
            }
        }).then(function() {           // on completion, restart
       setTimeout(chColor, 30000);  // function refers to itself
    });
})();

This will do the fetching and changing color(changing color is your part). Have this in mind that inside url you should enter right url to fetch data. setTimeout will prevent hammering server. Next part is your netstat view:

def netstat(request):
    results = []
    data_json = {}
    for line in snmpvalues: 
        if line == '1':
            data_json['flag']="1"
            results.append(data_json)
        else:
            data_json['flag']="0"
            results.append(data_json)

    final = json.dumps(results)

    return HttpResponse(final, 'application/json')

I think you are on the right way by this.

Upvotes: 1

Related Questions