Search code examples
pythondjangodjango-templatesmqttmosquitto

how update MQTT data in django template


I'm using paho-MQTT and I can receive messages and I can display the data in a template(html), but I can't update the message in realtime in the template(html). I want to update the value in the template when I get a new message from the mosquitto/topic.

from django.shortcuts import render
import paho.mqtt.client as mqtt

import json

valor_mqtt = 0

def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))

client.subscribe("mhub/hr")


def on_message(client, userdata, msg):
  global valor_mqtt
  valor_mqtt = (msg.payload)
  print(valor_mqtt)

def print_on_m(request):
  global valor_mqtt
  message = str(valor_mqtt)
  return render(request, 'home/index.html',{'context':message})



client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message


client.connect("mqtt.eclipseprojects.io", 1883, 60)

I'm passing print_on_m in urls.py to use {{context}} in home/index.html to show the data

PS: I don't want to use functions like "setInterval(function() {" or ".load(window.location.href" to update part of the web page after some time, I want to update only when I get new message from mosquitto/topic


Solution

  • The short answer is you don't do it in django.

    The template is only rendered once on the server side then sent to the client, it can't be updated once sent.

    What you can do is if your broker supports MQTT over WebSockets then you can use either the Paho JavaScript client or the MQTT.js client to subscribe to the broker from within the page running in the browser and get updates directly then update the page accordingly.